Search code examples
pythonpython-3.xoopmultiple-inheritance

Looking for replacement of these Magic Variable in Python


I designed this OOPs code with magic variable actually it feel little complicated so I want to rectify this code to simplest one without using Magic variable.Below code is Inheritance in Python.

And I'm in learning phase of OOPs concepts please suggest me best OOPs practice and which concepts are important in OOPs on perspective of programmer job.

 class Bike():
    bmodel = ''
    def __init__(self,**model):
        self.bmodel = model.get('bmodel')
        super(Bike,self).__init__(**model)

    def setmodelb(self,bmodel):
        self.bmodel = bmodel

    def getmodel(self):
        return self.bmodel

    def tostringb(self):
        print("Licence",self.lno,"is Bike and Model is",self.bmodel)

class Car():
    cmodel = ''
    def __init__(self,**model):
        self.cmodel = model.get('cmodel')
        super(Car,self).__init__()

    def setmodelc(self,cmodel):
        self.cmodel = cmodel

    def getmodel(self):
        return self.cmodel

    def tostringc(self):
        print("Licence",self.lno,"is Car and Model is",self.cmodel)

class Vehicle(Bike,Car):
    lno = ''
    def __init__(self,**model):
        self.lno = model.get('lno')
        super(Vehicle,self).__init__(**model)

    def setlno(self,lno):
        self.lno = lno

    def getlno(self):
        return self.lno

    def tostringv(self):
        print("Vehicle Licence is",self.lno)



 v = Vehicle()
    v.setlno("CALIFORNIA99")
    v.setmodelc("HONDA CITY")
    v.tostringc()
    v.tostringv()

OUTPUT

Licence CALIFORNIA99 is Car and Model is HONDA CITY
Vehicle Licence is CALIFORNIA99
[Finished in 0.1s]

Solution

  • Welcome to OOP. Your code seems complicated also because you are not following python conventions. Here are some essential reading:

    And for a more Pythonic code: PEP 20. Last but not least, avoid common pitfalls: Anti-patterns

    In your code, you can replace tostring by __repr__ method. This allows to do print(Car()). Also in python you do not need getter and setter as there are no public or private variables. So only define inside your __init__: self.model. You will be able to do:

    car = Car()
    car.model = ...