如果你真的想要@property
类变量的等价物,你必须自己构建描述符。
您几乎肯定不想这样做——请参阅 Lattyware 的回答,了解如何制作普通的实例变量,并将其中一个变成@property
.
但你可以这样做:
class IncrementOnGetDescriptor(object):
def __init__(self, initval=None):
self.val = initval
def __get__(self, obj, objtype):
self.val += 1
return self.val - 1
def __set__(self, obj, val):
self.val = val
class Foo(object):
a = IncrementOnGetDescriptor(2)
b = 2
现在你可以测试它了:
>>> f = Foo()
>>> f.a
2
>>> Foo.a
3
>>>> f.a
4
把它变成@classproperty
装饰器留给读者练习。
PS, this still isn't exactly like a normal class variable. Setting Foo.a = 10
will replace your magic auto-incrementing value with a normal 10
, while setting foo.a = 10
will update the class with an auto-incrementing 10
instead of storing an instance variable in f
. (I originally had the __set__
method raise AttributeError
, because normally you'd want an auto-incrementing magic variable be read-only, but I decided to show the more complex version just to show all the issues you have to deal with.)