2017-04-17 81 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__方法之间的唯一区别是参数的默认值,但我想这只是为了说明问题,对吗?

相关问题