在实例方法中更新Class变量 [英] Updating Class variable within a instance method
本文介绍了在实例方法中更新Class变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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 ),但是我给了我: /p>
I'm trying to update a class variable(var1) within a method(_init_) but I gives me:
TypeError: unbound method update() must be called with MyClass instance as first argument (got int instance instead)
之所以这样做,是因为我想通过调用print MyClass.var1来轻松访问类中的所有变量
I'm doing this because I want easy access to all variables in a class by calling print MyClass.var1
推荐答案
您正在混淆类和实例.
class MyClass(object):
pass
a = MyClass()
MyClass
是一个类,a
是该类的实例.您在这里的错误是update
是 instance方法.要从__init__
调用它,请使用:
MyClass
is 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)
或
MyClass.update(self, value)
或者,将update
设为 class方法:
@classmethod
def update(cls, value):
cls.var1 += value
这篇关于在实例方法中更新Class变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文