防止 Python 中类方法的重写属性?
我有以下代码:
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>
I have the following code:
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
The output is:
<property object at 0x01E55BD0>
24
Is there any way to prevent the setting of Test.spam
from overriding the property? I don't want to use Test.spam
to set the value of Test._spam
. The setter and getter have to remain as class methods, and I do not want to have to call Test.set_spam
.
The output should be:
<property object at 0x01E55BD0>
<property object at 0x01E55BD0>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想这可以防止开发人员意外覆盖
Test
的垃圾邮件属性。这就是你想要这个的原因吗?我不确定这是一个好主意(如果开发人员想要覆盖垃圾邮件属性怎么办?为什么要设置障碍?),但是......您可以使用元类。如果您没有为元类的属性提供 setter,则
Test.spam
将引发 AttributeError:But
raises
I suppose this stops developers from accidentally overwriting
Test
's spam property. Is that why you want this? I not sure that is a good idea (what if a developer wants to override the spam property? why throw up roadblocks?), but...You could use a metaclass. If you don't supply a setter for the metaclass's property, then
Test.spam
will raise an AttributeError:But
raises