我想创建一个在抽象基类中声明的“类属性”,然后在具体实现类中被覆盖,同时保持实现必须覆盖抽象基类的类属性的可爱断言。
尽管我看了一下这个问题,但我天真地尝试重新利用已接受的答案并没有奏效:
>>> import abc
>>> class ClassProperty(abc.abstractproperty):
... def __get__(self, cls, owner):
... return self.fget.__get__(None, owner)()
...
>>> class Base(object):
... __metaclass__ = abc.ABCMeta
... @ClassProperty
... def foo(cls):
... raise NotImplementedError
...
>>> class Impl(Base):
... @ClassProperty
... def foo(cls):
... return 5
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/2rs2ts/src/myproj/env/lib/python2.7/abc.py", line 94, in __new__
value = getattr(cls, name, None)
File "<stdin>", line 3, in __get__
TypeError: Error when calling the metaclass bases
unbound method foo() must be called with Impl instance as first argument (got nothing instead)
我对我应该做什么有点迷茫。有什么帮助吗?