有什么办法在Python中创建类属性吗? [英] Is there any way to create a class property in Python?

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

问题描述

以下因某种原因无法使用:

The following doesn't work for some reason:

>>> 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'

推荐答案

如果你有一种方法可以做到这一点,想让描述符属性在从对象X获取属性时触发,然后必须将描述符放在 type(X)。所以如果X是一个类,描述符必须放在类的类型中,也就是类的元类 - 不涉及欺骗,它只是一个完全一般的规则。

If you want the descriptor property to trigger when you get an attribute from object X, then you must put the descriptor in type(X). So if X is a class, the descriptor must go in the class's type, also known as the class's metaclass -- no "trickery" involved, it's just a matter of completely general rules.

或者,您可以编写自己的特殊用途描述符。请参见此处了解关于描述符的出色的操作方法条约。 编辑例如:

Alternatively, you might write your own special-purpose descriptor. See here for an excellent "how-to" treaty on descriptors. Edit for example:

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

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