2017-05-29 27 views
-1

我確定這件事很簡單,但我是新手。我有一組類。讓我們把如何將類值用作多個子類的默認值?

class Parent: 

    def __init__(self, name, color): 
     self.name = name 
     self.color = color 

class Mix: 
    def BMethod(self): 
     return '{0} is right' 

class Child(Parent, Mix): 
    def __init__(self, name, color, type): 
     self.type = 'AAA' 
     self.color = 'None' 
     super(Child,self).__init__(name,color) 

    def __str__(self): 
     return '{0} is a {1} {2}.'.format(self.name,self.color,self.type) 

class ChildSubType(Child, Mix): 
    def __init__(self, name, color, type): 
     color = 'None' 
     kind = super().kind 
     super(ChildSubType,self).__init__(name,color,type) 

    def __str__(self): 
     return "{0} is not a {1} {2}".format(self.name,self.color.self.type) 


childsubtype = ChildSubType(
    "Name1" 
    ,"White" 
) 

print(childsubtype) 

當我運行這段代碼,我得到的,上面寫着「TypeError: __init__() missing 1 required positional argument: 'type'

從本質上講,我的目標是,ChildSubType,我只能所需的,在名稱的錯誤,如果我沒有放入Color或Type,然後將它默認爲ChildSubType類的顏色值,並將其默認爲該類的Child類。

我不完全確定如何做到這一點。

我會認爲它與ChildSubType中的方法有關,但我並不是完全清楚該做什麼。在這一點上,我基本上遵循指示,並且已經擊中了這個路障。

對於它的價值,我也試着用Child運行它,而不使用ChildSubType,並且遇到了同樣的錯誤。我想我只是不知道如何使用類中的默認值。

編輯: 好吧,我想我已經得到它的工作。我更新了代碼,按照評論中的建議給它一個默認值。

這是我改變了:

Class Child(Parent, Mix): 
    def __init__(self, name, color, **type = 'AAA'**): 
     self.type = 'AAA' 
     self.color = 'None' 
     super(Child,self).__init__(name,color) 

    def __str__(self): 
     return '{0} is a {1} {2}.'.format(self.name,self.color,self.type) 

class ChildSubType(Child, Mix): 
    def __init__(self, name, color, **type = super(type)**): 
     color = 'None' 
     kind = super().kind 
     super(ChildSubType,self).__init__(name,color,type) 
+1

我認爲你可以在這裏使用關鍵字參數'__init __(...,類型=「默認」)' –

+0

這將使意義......但是,如果我不確定它在ChildSubType中,我怎麼會調用Child類的默認值? – phroureo

+0

默認'type'通過'super'調用傳遞。 –

回答

3

目前您在__init__方法中包含3個初始化變量,但同時使物體你逝去的只有2個。我會建議使用默認值,如下所示:

def __init__(self, name, color='None', type=None): 
+0

確實,我只是不會重寫內置的'type' – DeepSpace