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

8 投票
1 回答
935 浏览
提问于 2025-04-15 18:42

下面的代码出了一些问题,原因不明:

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

有没有其他方法可以解决这个问题,还是说我只能用一些特殊的技巧来处理呢?

1 个回答

7

如果你想让描述符 property 在从对象 X 获取属性时触发,那么你必须把这个描述符放在 type(X) 里。所以如果 X 是一个类,描述符就得放在这个类的类型里,也就是类的元类——这没有什么“花招”,只是一些非常普通的规则。

另外,你也可以自己写一个专用的描述符。想了解更多,可以查看这里,那是关于描述符的一个很棒的“如何做”的指南。编辑举个例子:

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,正如你所期望的那样。

撰写回答