基本上我想做这样的事情:
class foo:
x = 4
@property
@classmethod
def number(cls):
return x
Run Code Online (Sandbox Code Playgroud)
然后我希望以下工作:
>>> foo.number
4
Run Code Online (Sandbox Code Playgroud)
不幸的是,上述方法无效.而不是给我4它给我<property object at 0x101786c58>.有没有办法实现上述目标?
以下因某些原因无效:
>>> class foo(object):
... @property
... @classmethod
... def bar(cls):
... return "asdf"
...
>>> foo.bar
<property object at 0x1da8d0>
>>> foo.bar + '\n'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'property' and 'str'
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点,或者是我唯一可以采用某种元类技巧的替代方案?