我想要强制执行的是,当一个子类从父类继承,并且它重写父方法而不显式调用它时,会引发一个错误。 在初始化坏类或调用方法时可能会引发错误
目标是确保母类的用户执行母方法中存在的某些操作
范例
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
来修改类的创建方式,其思想是通过添加一个mother_method_called
标志来更改necessary_method
签名,该标志只有在调用Mother
版本时才会为真,否则它将引发一个Value Error
。例如在python3
中:相关问题 更多 >
编程相关推荐