Python 在实例方法中更新类变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20923411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:32:56  来源:igfitidea点击:

Updating Class variable within a instance method

pythonclassmethodsinstance

提问by f.rodrigues

class MyClass:
    var1 = 1

    def update(value):
        MyClass.var1 += value

    def __init__(self,value):
        self.value = value
        MyClass.update(value)

a = MyClass(1)

I'm trying to update a class variable(var1) within a method(_init_) but I gives me:

我正在尝试在方法(_ init_)中更新类变量(var1),但我给了我:

TypeError: unbound method update() must be called with MyClass instance as first argument (got int instance instead)

I'm doing this because I want easy access to all variables in a class by calling print MyClass.var1

我这样做是因为我希望通过调用 print MyClass.var1 轻松访问类中的所有变量

采纳答案by jonrsharpe

You are confusing classesand instances.

你混淆了实例

class MyClass(object):
    pass

a = MyClass()

MyClassis a class, ais an instance of that class. Your error here is that updateis an instance method. To call it from __init__, use either:

MyClass是一个类,a是该类的一个实例。您的错误是这update是一个实例方法。要从 调用它__init__,请使用:

self.update(value)

or

或者

MyClass.update(self, value)

Alternatively, make updatea class method:

或者,创建update一个类方法

@classmethod
def update(cls, value):
    cls.var1 += value

回答by damienfrancois

You need to use the @classmethoddecorator:

您需要使用@classmethod装饰器:

$ cat t.py 
class MyClass:
    var1 = 1

    @classmethod
    def update(cls, value):
        cls.var1 += value

    def __init__(self,value):
        self.value = value
        self.update(value)

a = MyClass(1)
print MyClass.var1
$ python t.py 
2