簡體   English   中英

在實例方法中更新類變量

[英]Updating Class variable within a instance method

class MyClass:
    var1 = 1

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

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

a = MyClass(1)

我正在嘗試在方法( _ init _ )中更新類變量( var1 ),但我給了我:

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

我這樣做是因為我希望通過調用 print MyClass.var1 輕松訪問類中的所有變量

你混淆了實例

class MyClass(object):
    pass

a = MyClass()

MyClass是一個類, a是該類a一個實例。 您的錯誤是update是一個實例方法 要從__init__調用它,請使用:

self.update(value)

MyClass.update(self, value)

或者,使update類方法

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

您需要使用@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM