我想要的是强制当子类从父类继承并且它重写父类方法而不显式调用它时,会引发错误。
在错误类的初始化或调用该方法时可能会引发错误。
目标是确保 Mother 类的用户执行 mother 方法中存在的一些操作。
Example
class Mother():
def necessary_method(self):
# do some necessary stuff
class GoodChild(Mother):
def necessary_method(self):
# necessary parent call
super().necessary_method()
class BadChild(Mother):
def necessary_method(self):
# no parent call
return
致电时:
good = GoodChild()
# works fine
bad = BadChild()
# exception could be raised here
good.necessary_method()
# works fine
bad.necessary_method()
# exception could be raised here
这真的可能吗?
欢迎任何答案或解决方法。
是的,这绝对是可能的,至少在运行时是这样。你可以创建一个Metaclass
修改类的创建方式,其想法是改变necessary_method
签名通过添加mother_method_called
标志只有当Mother
version 被调用,否则会引发Value Error
。例如在python3
:
class MotherMetaClass(type):
def __new__(cls, name, bases, attrs):
method_name = 'necessary_method'
mother_class_name = 'Mother'
original_necessary_method = attrs.get(method_name)
def necessary_method_validated(*args, **kwargs):
original_necessary_method(*args, **kwargs)
if name == mother_class_name:
cls.mother_method_called = True
else:
if not cls.mother_method_called:
raise ValueError(f'Must call "super()" when overriding "{method_name}".')
cls.mother_method_called = False
attrs[method_name] = necessary_method_validated
return super().__new__(cls, name, bases, attrs)
class Mother(metaclass=MotherMetaClass):
def necessary_method(self):
print('Parent method called.')
class GoodChild(Mother):
def necessary_method(self):
super().necessary_method()
print('Good child method called.')
class BadChild(Mother):
def necessary_method(self):
print("Bad child method called.")
a = GoodChild()
a.necessary_method() # it's going to work properly
b = BadChild()
b.necessary_method() # it's going to raise Value Error
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)