我想要执行的是强制执行以下操作:当子类从父类继承并且它重写父方法而不显式调用它时,将引发错误。错误可以在不良类的初始化时或在调用方法时引发。
目的是确保Mother类的用户执行了mother方法中存在的某些操作。
例子
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
这真的有可能吗?欢迎任何答案或解决方法。
是的,至少在运行时绝对有可能。U可以创建一个Metaclass
修改类创建方式的,其思想是necessary_method
通过添加mother_method_called
仅在Mother
调用版本时才为真的标志来更改签名,否则将引发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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句