所有类方法中的类变量访问

fer*_*ard 3 python class instance

我想要一个类变量,以便可以在所有实例中访问该值,但我还想在类中的方法中访问该变量.那可能吗?我试过这个,但它根本不起作用.

class myClass:
   myvariable = 1

   def add():
      myvariable+= 1

   def print1():
      print myvariable
Run Code Online (Sandbox Code Playgroud)

我想制作两个实例,一个只做add方法,另一个只做print1方法

Mar*_*ers 9

是的,只需访问类对象上的变量:

class myClass(object):
    myvariable = 1

    def add(self):
        myClass.myvariable += 1

    def print1(self):
        print myClass.myvariable
Run Code Online (Sandbox Code Playgroud)

或者如果要为每个子类设置它,请使用type(self):

class myClass(object):
    myvariable = 1

    def add(self):
        type(self).myvariable += 1

    def print1(self):
        print type(self).myvariable
Run Code Online (Sandbox Code Playgroud)

不同之处在于后者将在设置时在任何子类上创建单独的属性,从而屏蔽基类属性.这就像在实例上设置属性会掩盖class属性一样.

虽然你也可以通过()获取类属性,但是显式优于隐式,并且避免意外地被同名的实例属性屏蔽.设置类属性总是必须在类上完成; 设置它将创建或更新实例属性(不共享).selfprint self.myvariableself

object尽管如此,继承你的课程; 使用新式类有很多优点,至少type(self)不会实际返回类.在旧式类(不是继承object)中,你必须使用它self.__class__.

使用object作为基础还为您提供了第三个选项,即使用@classmethod装饰器的类方法; 当您只需要访问类对象而不是实例时,请使用这些.这些方法绑定到当前(子)类,因此它们对类属性的影响与使用相同type(self):

class myClass(object):
    myvariable = 1

    @classmethod
    def add(cls):
        cls.myvariable += 1

    @classmethod
    def print1(cls):
        print cls.myvariable
Run Code Online (Sandbox Code Playgroud)