在classmethods上使用property()
3 回答

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
有一個類有兩個類方法(使用classmethod()函數)來獲取和設置本質上是一個靜態變量。我嘗試使用property()函數,但它會導致錯誤。我能夠在解釋器中使用以下內容重現錯誤:
class Foo(object): _var = 5 @classmethod def getvar(cls): return cls._var @classmethod def setvar(cls, value): cls._var = value var = property(getvar, setvar)
我可以演示類方法,但它們不能作為屬性:
>>> f = Foo()>>> f.getvar()5>>> f.setvar(4)>>> f.getvar()4>>> f.varTraceback (most recent call last): File "<stdin>", line 1, in ?TypeError: 'classmethod' object is not callable>>> f.var=5Traceback (most recent call last): File "<stdin>", line 1, in ?TypeError: 'classmethod' object is not callable
是否可以將property()函數與classmethod修飾函數一起使用?
添加回答
舉報
0/150
提交
取消