【问题标题】:force subclass to implement property python强制子类实现属性python
【发布时间】:2021-04-02 11:02:25
【问题描述】:

尝试了force-implementing-specific-attributes-in-subclass的答案

但不起作用。这段代码仍然没有错误地通过。

#python version: 3.8.1
from abc import ABC, abstractmethod

class A(ABC):
    @property
    @abstractmethod
    def pr(self):
        return 0
    
class B(A):
    def pr(self):# not a property.
        return 5
    
b = B()

print(b.pr())

那么我怎样才能强制子类实现特定的属性(pr as above)?

【问题讨论】:

    标签: python inheritance properties subclass abstract-methods


    【解决方案1】:

    代码通过没有错误,因为您在子类中为抽象方法提供了具体实现,并且看起来(不确定)这是abc 唯一关心的事情。此外,如果您覆盖,则无法自动应用父类中的相同装饰器,您必须重复属性装饰器语法。

    我发现的最好的线程是this 和this。请完整阅读。

    此外,最近有一个 Python bug,看起来没有解决就关闭了(或者它是否重新打开了?)。也阅读那里的完整主题。有趣且相关。

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2020-06-19
      • 2017-01-23
      • 1970-01-01
      • 2012-02-01
      • 2017-01-13
      相关资源
      最近更新 更多