在父母中找出覆盖方法

发布于 2025-02-12 10:03:27 字数 769 浏览 1 评论 0原文

我熟悉OOP,并了解我们可以从基类继承并扩展 user_call_api 在子类中添加更多定义。但是我想知道是否有一种方法是在父班中,我们可以找出

  • 哪些方法被覆盖了(子类)
  • 的名称(儿童)类的名称已覆盖该方法
class Parent:

    def call_api(self):
        print("API is called")

    def use_call_api(self):
        # if it's overridden, find out in parent,
        # do something and then
        self.call_api()

        # if it's not overridden
        self.call_api()


class Child(Parent):

    def call_api(self):
        print("call_api")


class Child2(Parent):

    def call_api(self):
        print("call_api2")


class Child3(Parent):

    def call_api(self):
        print("call_ap3")

    def use_call_api(self):
        print("custom call_api")

I am familiar with OOP, and understand we can inherit from a base class and extend user_call_api in a child class adding more definitions to it. But I'm wondering is there a way that in parent class, we could find out

  • which methods are overridden (by child classes)
  • the name of (child) classes that have overridden the method
class Parent:

    def call_api(self):
        print("API is called")

    def use_call_api(self):
        # if it's overridden, find out in parent,
        # do something and then
        self.call_api()

        # if it's not overridden
        self.call_api()


class Child(Parent):

    def call_api(self):
        print("call_api")


class Child2(Parent):

    def call_api(self):
        print("call_api2")


class Child3(Parent):

    def call_api(self):
        print("call_ap3")

    def use_call_api(self):
        print("custom call_api")

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素手挽清风 2025-02-19 10:03:27

您可以拥有一个元素,该元素将覆盖__新的__ dunder-hodod,并将必要的信息(方法名称和类名称覆盖它覆盖的方法和类名称)置于其singleton属性中。

import re


class Inspect(type):
    implementations = {}

    def __new__(mcs, cls, args, kwargs):
        for attr in kwargs.keys():
            if not re.match(r"^__\w+__$", attr):
                mcs.implementations[attr] = (*mcs.implementations.get(attr, ()), cls)
        return type(cls, args, kwargs)

这些类(主要是从parent继承的子类)应使用Inspect metaclass。

Inspect.implementations将在应用程序启动后处于最终状态,并且在动态内存中声明所有类和功能以准备执行脚本。因此,您可以在parent中获得声明的其他方法,以获取覆盖当前方法的类列表,甚至是覆盖方法是否覆盖的方法。

import inspect


class Parent:

    @staticmethod
    def overridden() -> tuple:
        return Inspect.implementations.get(inspect.stack()[1].function, ())

    def call_api(self):
        print("API is called")

    def use_call_api(self):
        # if it's overridden, find out in parent,
        if self.overridden():
            print("use_call_api has been overridden in", self.overridden())

            # do something and then
            self.call_api()

        # if it's not overridden
        self.call_api()


class Child(Parent, metaclass=Inspect):

    def call_api(self):
        print("call_api")

    def use_call_api(self):
        pass


if __name__ == "__main__":
    p = Parent()
    p.use_call_api()

如果运行上述代码,则您会看到,当child覆盖 use_call_api方法时,覆盖>覆盖通过相同方法调用的方法parent将包含child,表明它覆盖了该方法。如果我们不实现use_call_api condy,则覆盖>覆盖将返回一个空元组,而如果self.overridden()代码>条件将行不通,并且会通过案例。

You can have a metaclass that will override the __new__ dunder-method and hold the necessary information (method name and class names that overrides it) into the singleton property of it.

import re


class Inspect(type):
    implementations = {}

    def __new__(mcs, cls, args, kwargs):
        for attr in kwargs.keys():
            if not re.match(r"^__\w+__
quot;, attr):
                mcs.implementations[attr] = (*mcs.implementations.get(attr, ()), cls)
        return type(cls, args, kwargs)

The classes (primarily the child classes inherited from Parent) should use Inspect metaclass.

The Inspect.implementations will be in their final state after the application starts and all classes and functions are declared in dynamic memory to be ready to execute the script. So you can get declare an additional method in the Parent to get the list of classes that override the current method or even was the method overridden or not.

import inspect


class Parent:

    @staticmethod
    def overridden() -> tuple:
        return Inspect.implementations.get(inspect.stack()[1].function, ())

    def call_api(self):
        print("API is called")

    def use_call_api(self):
        # if it's overridden, find out in parent,
        if self.overridden():
            print("use_call_api has been overridden in", self.overridden())

            # do something and then
            self.call_api()

        # if it's not overridden
        self.call_api()


class Child(Parent, metaclass=Inspect):

    def call_api(self):
        print("call_api")

    def use_call_api(self):
        pass


if __name__ == "__main__":
    p = Parent()
    p.use_call_api()

If you run the above code, then you will see that when Child overrides use_call_api method, then the overridden method called by the same method of the Parent will contain the Child, indicating that it overrides the method. If we do not implement use_call_api for Child, the overridden would return an empty tuple, and if self.overridden() condition would not work and will pass the case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文