python - 如何在不忘记在子类中添加属性装饰器的情况下覆盖抽象属性方法?

标签 python python-3.x properties abstract-class

如果我重写了一个抽象属性方法,但忘记指定它仍然是子类中的属性方法,我希望 Python 解释器对我大喊大叫。

class Parent(metaclass=ABCMeta):
  @property
  @abstractmethod
  def name(self) -> str:
    pass

class Child(Parent):
  @property # If I forget this, I want Python to yell at me.
  def name(self) -> str:
    return 'The Name'

if __name__ == '__main__':
  print(Child().name)

难道 Python 真的没有内置的方法来做到这一点吗?我真的必须创建自己的装饰器来处理此类行为吗?

最佳答案

您可以使用元类:

class Parent(type):
  def __new__(cls, name, bases, body):
    if 'name' not in body.keys() or body['name'].__class__.__name__ != 'property':
      raise TypeError(f"Can't instantiate class {name} without property name")
    return super().__new__(cls, name, bases, body)


class Child(metaclass=Parent):
  @property # If I forget this, raise TypeError
  def name(self) -> str: # also, name must be implemented
    return 'The Name'

if __name__ == '__main__':
  print(Child().name)

这会引发 TypeError: Can't instantiate class Child without property name - 当 @property 被注释掉时!

关于python - 如何在不忘记在子类中添加属性装饰器的情况下覆盖抽象属性方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63550842/

相关文章:

python - Linear_model在sklearn中代表什么?

python - 使用 ListView 的 Django 反向排序

python - subprocess.wait() 的返回码有多少种

java - 如何在 cfn-int 命令中将 EBS 磁盘添加到 AWS 实例

properties - 通知: Undefined property - how do I avoid that message in PHP?

python - 打开文件对象的大小

python - python3中的base64编码

python-3.x - 从文件加载数据并标准化

java - Spring Boot在application.properties中重命名server.port

Python 属性作为实例属性