我想创建一个在抽象基类中声明,然后在具体实现类中重写的“类属性”,同时保留实现必须重写抽象基类的类属性的可爱断言。在
虽然我看了看this question我天真的尝试重新确定目标,但接受的答案没有奏效:
>>> 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)
我有点不知道该做什么。有什么帮助吗?在
除了
@classmethod
修饰符之外,还需要使用它。在相关问题 更多 >
编程相关推荐