我有以下代码:
class Test(object):
_spam = 42
@classmethod
def get_spam(cls):
cls._spam
@classmethod
def set_spam(cls, value):
cls._spam = value
spam = property(get_spam, set_spam)
print Test.spam
Test.spam = 24
print Test.spam
输出结果为:
<property object at 0x01E55BD0>
24
有没有办法阻止设置Test.spam
覆盖财产?我不想使用Test.spam
来设置Test._spam
的值。 setter和getter必须保留为类方法,我不想调用Test.set_spam
。
输出应为:
<property object at 0x01E55BD0>
<property object at 0x01E55BD0>
答案 0 :(得分:1)
我认为这会阻止开发人员意外覆盖Test
的垃圾邮件属性。这就是你想要这个的原因吗?我不确定这是一个好主意(如果开发人员想要覆盖垃圾邮件属性怎么办?为什么要抛出障碍?),但是......
您可以使用元类。如果您没有为元类的属性提供setter,那么Test.spam
将引发AttributeError:
class MetaTest(type):
@property
def spam(cls):
return cls._spam
class Test(object):
__metaclass__=MetaTest
_spam = 42
@classmethod
def get_spam(cls):
cls._spam
@classmethod
def set_spam(cls, value):
cls._spam = value
spam = property(get_spam, set_spam)
print Test.spam
# 42
但是
Test.spam = 24
加注
AttributeError: can't set attribute