I'm wanting to create a subclass of a subclass (Barrier is a type of wall, which is a type of obstacle), and I'm wanting the barrier to have the same init method as wall with the exception that the self.type = 'barrier', but I'm not sure how to do this (I'm very new to programming so I'm sorry if this is very simple but I haven't been able to find an answer I understand). So far I have:
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"
How do I change it so that class Barrier has identical contents of the init method as Walls do, except their "self.type = 'barrier'"?
Just override that one attribute after invoking the Wall
version:
class Barrier(Wall):
def __init__(self, origin, end):
super().__init__(origin, end)
self.type = 'barrier'
def __str__(self):
return "Barrier obstacle"
You may want to consider using class attributes instead however; none of your instance attributes are dynamic and specific to each instance of the class. The type
attribute of each of these classes surely won't change from one instance to another:
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With