如何在调用子方法时强制父方法调用?

2024-10-02 02:25:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要强制执行的是,当一个子类从父类继承,并且它重写父方法而不显式调用它时,会引发一个错误。 在初始化坏类或调用方法时可能会引发错误

目标是确保母类的用户执行母方法中存在的某些操作

范例

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

这真的有可能吗? 欢迎任何答案或解决方法


Tags: 方法selfdef错误callmethodclassparent
1条回答
网友
1楼 · 发布于 2024-10-02 02:25:30

是的,这是绝对可能的,至少在运行时是这样。您可以创建一个Metaclass来修改类的创建方式,其思想是通过添加一个mother_method_called标志来更改necessary_method签名,该标志只有在调用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

相关问题 更多 >

    热门问题