我怎么组合abc.抽象属性用classmethod生成“抽象类属性”?

2024-06-26 12:36:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个在抽象基类中声明,然后在具体实现类中重写的“类属性”,同时保留实现必须重写抽象基类的类属性的可爱断言。在

虽然我看了看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)

我有点不知道该做什么。有什么帮助吗?在


Tags: inselfgetreturn属性foodefline
1条回答
网友
1楼 · 发布于 2024-06-26 12:36:24

除了@classmethod修饰符之外,还需要使用它。在

class Impl(Base):
    @ClassProperty
    @classmethod
    def foo(cls):
        return 5

In [11]: Impl.foo
Out[11]: 5

相关问题 更多 >