Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding part of the __init__ method in a subclass in Python 2

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'"?

like image 779
J Dope Avatar asked Sep 20 '25 18:09

J Dope


1 Answers

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'
like image 172
Martijn Pieters Avatar answered Sep 22 '25 08:09

Martijn Pieters