Skip to main content
 首页 » 编程设计

python之在 Python 2 的子类中重写部分 __init__ 方法

2025年05月04日16tintown

我想创建一个子类的子类(Barrier 是一种墙,是一种障碍),我希望障碍具有相同的init 方法作为墙,除了 self.type = 'barrier',但我不知道该怎么做(我对编程很陌生,所以很抱歉,如果这很简单,但我没能做到找到我理解的答案)。到目前为止,我有:

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" 

我如何更改它,以便类 Barrier 具有与 Walls 相同的 init 方法内容,除了它们的“self.type = 'barrier'”?

请您参考如下方法:

在调用 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'