繁体   English   中英

在 python 中继承超过 1 个父 class

[英]Inheriting more than 1 parent class in python

I am trying to inherit 2 classes as parent class in a child class both have different class variables class A has a,b while class B has c,d,e they are the parent to class AB(A,B) now i want to制作 AB class 的 object 但我无法理解如何在我尝试创建 AB class 的 object 时传递值

class A:
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def testa(self):
        print('inside A')
class B:
    def __init__(self,c,d,e):
        self.c = c
        self.d = d
        self.e = e
    def testb(self):
        print('inside B')

class AB(A,B):
    def __init__(self,*args):
        A.__init__(self,*args)
        B.__init__(self,*args)

obj = AB(1,2,3) # 这是抛出错误

发生这种情况是因为您使用 *args 参数调用 A 和 B 类的__init__方法,这导致所有 arguments 作为单个元组传递。 发生这种情况是因为您使用 *args 参数调用 A 和 B 类的__init__方法,这导致所有 arguments 作为单个元组传递。 要解决此问题,您可以在 AB class 中定义__init__方法并将变量的值接受为单独的 arguments,如下所示:

class AB(A,B):
    def __init__(self, a, b, c, d, e):
        A.__init__(self, a, b)
        B.__init__(self, c, d, e)

现在您可以像这样传递值:

obj = AB(1, 2, 3, 4, 5)

*args将始终解压缩所有值。 由于A只需要 2 个值,因此当您传递 3 个值时,它会抛出错误。 如果要将前 2 个元素传递给A ,则要将args限制为 2 个元素,请使用slicing [:2]

所以你的ABinit应该是这样的:

class AB(A,B):
    def __init__(self, *args):
        A.__init__(self, *args[:2])
        B.__init__(self, *args)

此外,您的方法testatestb会遇到错误,因为它们缺少始终传递给实例方法的self

只需将self添加到两种方法中即可避免TypeError

def testa(self):
        print('inside A')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM