如果我重写了一个抽象属性方法,但忘记指定它仍然是子类中的属性方法,我希望 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/