Home > Mobile >  How to Access Parent class variable in Python and Call Parent Method using Child Object
How to Access Parent class variable in Python and Call Parent Method using Child Object

Time:09-24

I am practicing Python Inheritance. I am not able to access and parent class variable in child class and not able to call parent class using child's object.

class carmodel():
    def __init__(self, model):
        self.model=model
    def model_name(self):
        print("Car Model is", self.model)
        
class cartype(carmodel):
    def __init__(self, typ):
        super().__init__(self, model)
        self.typ = typ
    def ctyp(self):
        print(self.model, "car type is",self.typ)
car1=cartype("Sports")
car1.ctyp()
car1.model_name("Tesla Plaid")

CodePudding user response:

Is this what you want?
Few udpates in your code: function model_name() is expected to print the model_name assigned to the car, and as carmodel is parent of cartype, the model info needs to be passed to parent class and store it in self. So initialize cartype with type and model and pass this model to parent class as done in the code below:

class carmodel():
    def __init__(self, model):
        self.model=model
    def model_name(self):
        print("Car Model is", self.model)
        
class cartype(carmodel):
    def __init__(self, typ, model):
        super().__init__(model)
        self.typ = typ
    def ctyp(self):
        print(self.model, "car type is",self.typ)
car1=cartype("Sports", "Tesla Plaid")
car1.ctyp()
car1.model_name()

Output:

Tesla Plaid car type is Sports
Car Model is Tesla Plaid

CodePudding user response:

Here's a reconstruction of your code that you might find useful:-

class carmodel():
    def __init__(self, model):
        self.model=model
    def model_name(self):
        return f'Model={self.model}'
        
class cartype(carmodel):
    def __init__(self, typ, model):
        super().__init__(model)
        self.typ = typ
    def ctyp(self):
        return f'Model={self.model}, type={self.typ}'

car=cartype("Sports", 'Plaid')
print(car.ctyp())
print(car.model_name())
  • Related