Updating Class variable within a instance method

前端 未结 2 1839
迷失自我
迷失自我 2021-02-05 09:50
class MyClass:
    var1 = 1

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

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


        
相关标签:
2条回答
  • 2021-02-05 10:11

    You need to use the @classmethod decorator:

    $ 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
    
    0 讨论(0)
  • 2021-02-05 10:15

    You are confusing classes and instances.

    class MyClass(object):
        pass
    
    a = MyClass()
    

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

    self.update(value)
    

    or

    MyClass.update(self, value)
    

    Alternatively, make update a class method:

    @classmethod
    def update(cls, value):
        cls.var1 += value
    
    0 讨论(0)
提交回复
热议问题