类属性返回Empty

问题描述 投票:0回答:1

我创建了一个类并在init方法中初始化了该属性。我正在更新方法中的class属性。创建对象并尝试打印class属性后,它返回空。请告诉我哪里出错了。

     class Counter(object):
            def __init__(self, start=1):
                self.val = start
                self.params = {}

            def increment(self):
                self.val += 1
                self.params['name'] = 'sameer'
                self.params['age'] = 26
                return

            def decrement(self):
                self.val -= 1
                return
 c = Counter()
 print(c.params)

Output:
{}
python-3.x
1个回答
0
投票

你只在.params方法填充你的increment() dict并且从不调用这个方法,所以显然它保持空白。只需致电c.increment()并重新打印c.params

作为旁注:

我正在更新类属性(...)尝试打印类属性(...)

在您的示例中,params是一个实例属性(每个实例都有自己的param dict),而不是“类属性”。在Python中,“类属性”是属于类本身的属性,并且在类的所有实例之间共享,即:

class Foo(object):
    shared = [] # this is a class attribute

    def __init__(self):
        self.owned = [] # this is an instance attribute
© www.soinside.com 2019 - 2024. All rights reserved.