簡體   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