是否可以从Python中的构造函数内增加/访问类变量?

时间:2018-01-17 20:55:06

标签: python python-2.7

每次实例化一个类时,我想通过计数器跟踪。我试图通过从类'consructor ala:

中增加一个定义为类变量的计数器来做到这一点。
class Cl:
   cntr = 0
   def __init__(self):
      cntr += 1

但是,当我实例化该类时,我得到一个“UnboundLocalError:局部变量'cntr'在分配之前引用”我假设这是因为构造函数将其视为局部变量。如何从Python 2.7中的方法或构造函数中引用类变量?

2 个答案:

答案 0 :(得分:4)

您只需通过类调用变量:

class Cl:
    cntr = 0
    def __init__(self):
        Cl.cntr += 1  # <---Like this


print(Cl().cntr)  # prints 1
print(Cl().cntr)  # prints 2
print(Cl().cntr)  # prints 3

答案 1 :(得分:2)

class Foo:
    n = 0
    def __init__(self):
        self._increment()

    @classmethod
    def _increment(cls):
        cls.n += 1

f1 = Foo()
f2 = Foo()

>>> f1.n
2

>>> f2.n
2