我如何将 abc.abstractproperty 与类方法结合起来制作 "abstract class property"?
How can I combine abc.abstractproperty with a classmethod to make an "abstract class property"?
我想创建一个 "class property",它在抽象基础 class 中声明,然后在具体实现 class 中被覆盖,同时保持可爱的断言实现必须覆盖抽象基础 class' class 属性.
虽然我看了一下 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
装饰器之外,您还需要使用它。
class Impl(Base):
@ClassProperty
@classmethod
def foo(cls):
return 5
In [11]: Impl.foo
Out[11]: 5
我想创建一个 "class property",它在抽象基础 class 中声明,然后在具体实现 class 中被覆盖,同时保持可爱的断言实现必须覆盖抽象基础 class' class 属性.
虽然我看了一下 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
装饰器之外,您还需要使用它。
class Impl(Base):
@ClassProperty
@classmethod
def foo(cls):
return 5
In [11]: Impl.foo
Out[11]: 5