J D*_*ope 4 python class subclass
我想创建子类的子类(Barrier 是墙的一种类型,是障碍物的一种),并且我希望 Barrier 具有与 wall 相同的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"
Run Code Online (Sandbox Code Playgroud)
我如何更改它,以便 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"
Run Code Online (Sandbox Code Playgroud)
然而,您可能需要考虑使用类属性;您的实例属性都不是动态的且特定于类的每个实例。这些类中的每一个的属性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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6057 次 |
| 最近记录: |