从Python中的两个不同类重载方法的更好方法

2024-03-29 02:27:22 发布

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

我有两个不能重新定义的父类(比如,AB),我需要使用完全相同的方式重载方法(以便获得,比如,BetterABetterB)。 我可以为这两个类复制代码,但我对此并不满意。 在Python3.6中,我认为可以使用多重继承和提供程序类来消除这种情况。 这就是我目前所得到的:

# here are the initial classes I cannot edit
class A:
    def __init__(self, a=0):
        self.a = a

class B:
    def __init__(self, b=0):
        self.b = b

# here is the provider class
class Provider:
    def __init__(self, c, *args, **kwargs):
        self.c = c

        # more code here

        self.init_child(*args, **kwargs)

# here are the new classes
class BetterA(Provider, A):
    def init_child(self, *args, **kwargs):
        A.__init__(*args, **kwargs)

class BetterB(Provider, B):
    def init_child(self, *args, **kwargs):
        B.__init__(*args, **kwargs)

if __name__ == '__main__':
    a = BetterA(8, a=10)
    b = BetterB(10, b=8)

这很管用,但不是很优雅… 特别是,如果我想覆盖更多的方法(总是以同样的方式),我必须在BetterABetterB中调用它们

如果有更好的方法实现我的目标


Tags: the方法selfchildhereinitdef方式
1条回答
网友
1楼 · 发布于 2024-03-29 02:27:22

super()适用于多重继承:

# here is the provider class
class Provider:
    def __init__(self, c, *args, **kwargs):
        self.c = c

        # more code here

        super().__init__(*args, **kwargs)

# here are the new classes
class BetterA(Provider, A):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class BetterB(Provider, B):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

if __name__ == '__main__':
    a = BetterA(8, a=10)
    b = BetterB(10, b=8)

如果Better*.__init__除了调用super方法之外没有做任何事情,那么您不需要重新定义它:

# here are the new classes
class BetterA(Provider, A):
    pass

class BetterB(Provider, B):
    pass

根据是否需要在Better*类型中实现更多功能,您可能更喜欢的另一个选项是创建类的函数:

def provided(cls):
    class Provided(cls):
        def __init__(self, c, *args, **kwargs):
            self.c = c

            # more code here

            super().__init__(*args, **kwargs)

    return Provided


BetterA = provided(A)
BetterB = provided(B)

相关问题 更多 >