中创建只读类属性

中创建只读类属性

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

问题描述

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

class foo:x = 4@财产@类方法定义编号(cls):返回 x

然后我希望以下内容起作用:

>>>foo.number4

不幸的是,上述方法不起作用.它没有给我 4,而是给了我 .有什么办法可以达到上述目的吗?

解决方案

property 描述符总是在从类访问时返回自身(即当 instanceNone 在它的 __get__ 方法中).

如果这不是您想要的,您可以编写一个始终使用类对象(owner)而不是实例的新描述符:

>>>类类属性(对象):... def __init__(self, getter):... self.getter=吸气剂... def __get__(self, instance, owner):...返回 self.getter(owner)...>>>类 Foo(对象):... x= 4... @classproperty...定义数字(cls):...返回 cls.x...>>>Foo().number4>>>编号4

Essentially I want to do something like this:

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

Then I would like the following to work:

>>> foo.number
4

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?

解决方案

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

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 中创建只读类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:30