2017-01-04 110 views
3

首先,我知道有來實現繼承這樣一個正確的做法:爲什麼我不能像這樣實現繼承?

class Parent(): 
    def __init__(self, last_name, eye_color): 
     self.last_name = last_name 
     self.eye_color = eye_color 

class Child(Parent): 
    def __init__(self, last_name, eye_color, number_of_toys): 
     Parent.__init__(self, last_name, eye_color) 
     self.number_of_toys = number_of_toys 

miley_cyrus = Child("Cyrus", "Blue", 5) 
print(miley_cyrus.last_name) 
print(miley_cyrus.number_of_toys) 

當我運行的代碼段,有一個

Cyrus 
5 

然而,當我改變結果7號線進入:

self = Parent(last_name, eye_color) 

和代碼已經成爲:

class Parent(): 
    def __init__(self, last_name, eye_color): 
     self.last_name = last_name 
     self.eye_color = eye_color 

class Child(Parent): 
    def __init__(self, last_name, eye_color, number_of_toys): 
     self = Parent(last_name, eye_color) 
     self.number_of_toys = number_of_toys 

miley_cyrus = Child("Cyrus", "Blue", 5) 
print(miley_cyrus.last_name) 
print(miley_cyrus.number_of_toys) 

,我運行一段代碼,有一個錯誤指示:

Traceback (most recent call last): 
    File "/Users/Echo/Documents/IT/Udacity/python/7.Inheritance/inherentance.py", line 12, in <module> 
    print(miley_cyrus.last_name) 
AttributeError: Child instance has no attribute 'last_name' 

這有什麼錯呢?提前致謝。

+0

'self = Parent'?你想爲自己的父對象? – vks

+0

試試這個self.obj = Parent(last_name,eye_color) –

+1

請注意,由於不相關的原因,最好在Python中繼承'object'而不是無('class Parent(object):')。 –

回答

3

我不確定你在做什麼,但你可以通過這種方式獲得預期的結果。

class Parent(): 
    def __init__(self, last_name, eye_color): 
     self.last_name = last_name 
     self.eye_color = eye_color 

class Child(Parent): 
    def __init__(self, last_name, eye_color, number_of_toys): 
     self.obj = Parent(last_name, eye_color) 
     self.number_of_toys = number_of_toys 

miley_cyrus = Child("Cyrus", "Blue", 5) 
print(miley_cyrus.obj.last_name) 
print(miley_cyrus.number_of_toys) 

self = Parent應該self.some_variable = Parent

+0

這是好的..! –

+1

注意:在這種情況下,根本不需要繼承「Parent」。只要做簡單的'class Child(object):' –

1

我認爲回答這個問題並沒有真正得到實際的問題。在我的解釋中,你認爲self是某種你可以手動改變的上下文。

您是否知道,self確實是您創建的實例?重新分配它不僅會令人困惑,而且會導致錯誤 - 即使分配給參數也是不可能的。

您可以執行這段代碼這表明你,你正試圖變異miley_cyrusParentChild初始化內部:

class Parent(object): 
    def __init__(self, last_name, eye_color): 
     self.last_name = last_name 
     self.eye_color = eye_color 

class Child(Parent): 
    def __init__(self, last_name, eye_color, number_of_toys): 
     # hex(id(self)) -> 0x7fe2325a7da0 
     self.number_of_toys = number_of_toys 

miley_cyrus = Child("Cyrus", "Blue", 5) # hex(id(miley_cyrus)) -> 0x7fe2325a7da0 

而且我認爲,長期初始化是非常重要的在這裏,因爲你可能會與傳統語言混淆。 Python有一個獨立的魔術方法,它負責實際創建對象(__new__)。在調用__init__時 - 您已經在實例化的對象上運行。這就是爲什麼__new__需要一個類對象而不是self

相關問題