【问题标题】:How can I combine abc.abstractproperty with a classmethod to make an "abstract class property"?如何将 abc.abstractproperty 与 classmethod 结合起来制作“抽象类属性”?
【发布时间】:2015-03-15 05:00:45
【问题描述】:

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

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

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

【问题讨论】:

    标签: python abc


    【解决方案1】:

    除了 @classmethod 装饰器之外,您还需要使用它。

    class Impl(Base):
        @ClassProperty
        @classmethod
        def foo(cls):
            return 5
    
    In [11]: Impl.foo
    Out[11]: 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2015-01-04
      • 1970-01-01
      • 2021-06-03
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多