add a getter to a subclass in python

To add a getter method to a subclass in python, you can simply define a method that returns the value of the attribute you want to access. Here's an example:

main.py
class Vehicle:
    def __init__(self, color):
        self.color = color
    
class Car(Vehicle):
    def __init__(self, make, model, color):
        super().__init__(color)
        self.make = make
        self.model = model

    def get_make(self):
        return self.make
    
    def get_model(self):
        return self.model
332 chars
16 lines

In this example, we have a Vehicle class and a Car subclass that inherits from it. We've added make and model attributes to the Car subclass, and defined getter methods get_make and get_model to access them.

You can now create a Car object and use the getter methods to access its make and model attributes:

main.py
my_car = Car("Toyota", "Corolla", "blue")
print(my_car.get_make())
print(my_car.get_model())
93 chars
4 lines

Output:

main.py
Toyota
Corolla
15 chars
3 lines

gistlibby LogSnag