在Python 2的子类中覆盖__init__方法的一部分

问题描述:

我想创建一个子类的子类(Barrier是一种类型的墙,这是一种障碍),并且我想要屏障有相同的初始化作为墙的方法,但self.type ='障碍'的例外,但我不知道如何做到这一点(我对编程非常新,所以我很抱歉,如果这是非常简单的但我一直无法找到我理解的答案)。到目前为止,我有:在Python 2的子类中覆盖__init__方法的一部分

class Obstacle: 
    def __init__(self, type): 
     self.type = 'obstacle' 

    def __str__(self): 
     return "obstacle" 

class Wall(Obstacle): 

    def __init__(self, origin, end): 

     self.type = 'wall' 
     self.origin = origin 
     self.end = end 

     # etc.... (i.e. there are more things included in here which the 
     # that the barrier also needs to have (like coordinate vectors etc.) 

class Barrier(Wall): 

    def __str__(self): 
     return "Barrier obstacle" 

我如何改变它,这样类障碍有初始化方法的相同内容的墙壁做,除非他们的“self.type =‘壁垒’”?

只需重写一个属性调用Wall版本之后:但是

class Barrier(Wall): 
    def __init__(self, origin, end): 
     super().__init__(origin, end) 
     self.type = 'barrier' 

    def __str__(self): 
     return "Barrier obstacle" 

你可能要考虑使用类属性代替;没有任何实例属性是动态的,并且对于每个类的实例都是特定的。每个类的type属性肯定不会改变从一个实例到另一个:

class Obstacle: 
    type = 'obstacle' 

    def __str__(self): 
     return self.type 

class Wall(Obstacle): 
    type = 'wall' 

    def __init__(self, origin, end): 
     super().__init__() 
     self.origin = origin 
     self.end = end 
     # etc.... (i.e. there are more things included in here which the 
     # that the barrier also needs to have (like coordinate vectors etc.) 

class Barrier(Wall): 
    type = 'barrier' 
+0

我刚刚尝试过这样做,但在尝试创建类的实例时遇到错误,因为它表示Barrier的__init__只有一个参数,但我还需要给出起点和终点? –

+0

@JDope:我的错误,改正了。 –

由于“类型”似乎取决于类,我根本就没有type属性的对象,但在一流水平

class Obstacle: 

    type = 'obstacle' 

    def __init__(self): 
     # do something 
     pass 

    def __str__(self): 
     return "obstacle" 

class Wall(Obstacle): 

    type = 'wall' 

    def __init__(self, origin, end): 
     super().__init__() 
     self.origin = origin 
     self.end = end 

class Barrier(Wall): 

    type = 'barrier' 

    def __str__(self): 
     return "Barrier obstacle"

而且你最好叫super().__init__方法,如果你将其覆盖。因为否则在类层次结构中更高的初始化将不会发生(这有时是期望的行为,但通常不是)。

这样做的好处是它 - 至少在我看来 - 更优雅。因为这里很明显,每个类都定义了type。但是此外它会减少使用的内存量。由于我们每个类存储一个属性,因此我们每个对象存储一个而不是

但是,如果您想改变单个对象的属性,这仍然是可能的。例如:

>>> obs1 = Obstacle() 
>>> weird_obs = Obstacle() 
>>> weird_obs.type = 'weird obstacle' 
>>> obs2 = Obstacle() 
>>> obs1.type 
'obstacle' 
>>> weird_obs.type 
'weird obstacle' 
>>> obs2.type 
'obstacle' 

因此,我们仍然可以灵活地将特定类型添加到特定对象。但默认情况下,如果我们查询障碍type,它将执行回退并返回在类级别上定义的type

+1

只是为了防止OP不理解:在__init__中使用'self.type ='barrier''和类齿列下的'type ='barrier''之间的区别在于后者创建了一个“静态“变量。这基本上意味着'type'属性将在Barrier的所有实例*享。这样做的好处是,由于'type ='barrier''永远不会改变每个实例,所以您可以让所有实例共享一个属性,而不是让每个实例都拥有它自己的属性。 –