我有一个类有两个类方法(使用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)
Run Code Online (Sandbox Code Playgroud)
我可以演示类方法,但它们不能作为属性:
>>> f = Foo()
>>> f.getvar()
5
>>> f.setvar(4)
>>> f.getvar()
4
>>> f.var
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
>>> f.var=5
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'classmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
是否可以将property()函数与classmethod修饰函数一起使用?
使用python属性,我可以这样做
obj.y
Run Code Online (Sandbox Code Playgroud)
调用函数而不是仅返回值.
有没有办法用模块做到这一点?我有一个我想要的案例
module.y
Run Code Online (Sandbox Code Playgroud)
调用函数,而不是只返回存储在那里的值.