我想创建一个子类的子类(屏障是一种墙,它是一种障碍物(,我希望屏障具有与墙相同的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"
如何更改它,以便类屏障具有与墙壁相同的init方法内容,除了它们的"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'
由于"类型"似乎依赖于类,因此我根本不会将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
。