防止Python中类方法的覆盖属性?

时间:2011-08-05 20:50:34

标签: python oop properties class-method

我有以下代码:

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>

1 个答案:

答案 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