防止 Python 中类方法的重写属性?

发布于 2024-11-28 10:39:34 字数 668 浏览 4 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱格式化 2024-12-05 10:39:34

我想这可以防止开发人员意外覆盖 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

But

Test.spam = 24

raises

AttributeError: can't set attribute

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:

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

But

Test.spam = 24

raises

AttributeError: can't set attribute
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文