簡體   English   中英

在python中從派生構造函數調用基本構造函數

[英]calling base constructor from derived constructor in python

為了執行它應該做什么

class parent():
    age=None
    name=None
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def printout(self):
        print(self.name)
        print(self.age) 

class child(parent):
    def __init__(self,name,age,gender):
        super(parent,self).__init__(self.name,self.age)
        print gender

c=child("xyz",22,"male")
c.printout()

我是python世界的新手,無法找出問題所在

super()僅適用於新型類; object添加到parent類的基類中:

class parent(object):

您可能還需要調整您的super()調用。 您需要提供當前類而不是parent類來開始搜索,並且在調用__init__時, self.nameself.age仍設置為None ,但是您似乎想傳遞nameage參數:

def __init__(self, name, age, gender):
    super(child, self).__init__(name, age)
    print gender

通過這些更改,代碼可以工作:

>>> c = child("xyz", 22, "male")
male
>>> c.printout()
xyz
22

您需要從object繼承以使super()工作,將self.nameself.age傳遞給super()調用時,它們也始終為None

class parent(object):

和:

super(child, self).__init__(name, age)

super()僅適用於新樣式類(在Python3中,一切都是新樣式)。 所以你需要

class parent(object):

同樣在對super的調用中,第一個參數是類的名稱而不是父類的名稱。 子班的電話應該是

super(child, self).__init__(name, age)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM