如何在Python中创建只读类属性? [英] How to create a read-only class property in Python?

查看:287
本文介绍了如何在Python中创建只读类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想做这样的事情:

Essentially I want to do something like this:

class foo:
    x = 4
    @property
    @classmethod
    def number(cls):
        return x

然后我想要以下工作:

>>> foo.number
4

不幸的是,上述方法不起作用。而不是给我 4 它给我< property object at 0x101786c58> 。有没有办法实现上述?

Unfortunately, the above doesn't work. Instead of given me 4 it gives me <property object at 0x101786c58>. Is there any way to achieve the above?

推荐答案

属性描述符当从类中访问时(即实例 __ get__中 方法)。

The property descriptor always returns itself when accessed from a class (ie. when instance is None in its __get__ method).

如果这不是你想要的,你可以写一个新的描述符,总是使用类对象( owner )代替实例:

If that's not what you want, you can write a new descriptor that always uses the class object (owner) instead of the instance:

>>> class classproperty(object):
...     def __init__(self, getter):
...         self.getter= getter
...     def __get__(self, instance, owner):
...         return self.getter(owner)
... 
>>> class Foo(object):
...     x= 4
...     @classproperty
...     def number(cls):
...         return cls.x
... 
>>> Foo().number
4
>>> Foo.number
4

这篇关于如何在Python中创建只读类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆