2017-04-17 80 views
-2

我試圖讓Child類調用並使用Parent的__init__method,除了在Child中使用super()方法之外,還有其他一些方法可以做到這一點嗎?我被告知要避免使用super()是可能的,因此我想知道。除了super()之外,還有其他一些方法可以調用Parent的__init__方法嗎?

# -*- coding: utf-8 -*- 

class Room(object): 

    def __init__(self, current_room): 
     self.current_room = current_room 
     print("You are now in Room #{}".format(self.current_room)) 

class EmptyStartRoom(Room): 

    def __init__(self, current_room=1): 
     super().__init__(current_room) 

class ChestRoomKey1(Room): 

    def __init__(self, current_room=2): 
     super().__init__(current_room) 

a_room = EmptyStartRoom() 
other_room = ChestRoomKey1() 

從上面的代碼中,我得到:

您現在在房間#1

您現在在房間#2

+2

爲什麼要避免使用'super()'? – Blender

+0

@Blender如果我不確定自己在做什麼,我應該避免使用它,如果可能的話,我會被告知有使用super()的商品和不便之處,所以作爲初學者。也許情況並非如此? –

回答

0

您可以直接調用基類,同時也傳遞self參數:

# -*- coding: utf-8 -*- 
class Room(object):  
    def __init__(self, current_room): 
     self.current_room = current_room 
     print("You are now in Room #{}".format(self.current_room)) 

class EmptyStartRoom(Room):  
    def __init__(self, current_room=1): 
     Room.__init__(self, current_room) 

class ChestRoomKey1(Room):  
    def __init__(self, current_room=2): 
     Room.__init__(self, current_room) 

a_room = EmptyStartRoom() 
other_room = ChestRoomKey1() 

您還應該檢查出this後,告訴你爲什麼你應該考慮使用super()當你開始做多繼承,但現在,這兩種方式都很好。

0

不要試圖找到替代品。

它們可能是可能的,但最終會生成硬編碼超類(請參閱@abccd答案)或使用「您自己的MRO解決方案」。但是從長遠來看,避免super()將變成維護噩夢(現在很難實現)。

在你的情況下,你做的一切都是正確的!這個例子有點奇怪,因爲__init__方法之間的唯一區別是參數的默認值,但我想這只是爲了說明問題,對嗎?

相關問題