python - 有没有办法在 Python 中创建类属性?

标签 python class properties class-method

由于某些原因,以下内容不起作用:

>>> class foo(object):
...     @property
...     @classmethod
...     def bar(cls):
...             return "asdf"
... 
>>> foo.bar
<property object at 0x1da8d0>
>>> foo.bar + '\n'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'property' and 'str'

有没有办法做到这一点,或者我唯一的选择是求助于某种元类诡计?

最佳答案

如果您希望描述符 property 在您从对象 X 获取属性时触发,那么您必须将描述符放在 type(X) 中。因此,如果 X 是一个类,则描述符必须属于类的类型,也称为类的元类——不涉及任何“技巧”,这只是一个完全通用规则的问题。

或者,您可以编写自己的专用描述符。参见 here一个关于描述符的优秀“操作方法”条约。 编辑例如:

class classprop(object):
  def __init__(self, f):
    self.f = classmethod(f)
  def __get__(self, *a):
    return self.f.__get__(*a)()

class buh(object):
  @classprop
  def bah(cls): return 23

print buh.bah

根据需要发出 23

关于python - 有没有办法在 Python 中创建类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2173206/

相关文章:

python - 如何在 QMessageBox 小部件中居中文本和按钮

python - 从单一导入访问 python 应用程序中的全局变量

python - pandas - 将两个数据框放入一列

php - 多次调用一个方法,是否有更有效的方法?

javascript - 使用 DontEnum 设置自定义属性

c# - 使用属性作为工厂方法

python - 如何让 PyC​​harm 从函数定义中获取类型提示并在文档字符串中填充类型值?

python - 为什么在声明子类的对象时不调用父类(super class)的构造函数?

css - 为什么 CSS 类声明不适用于标记的 <div>?

vbscript - 如何将属性指定为 VbScript 类的默认属性