在 Python 中寻找这些魔法变量的替代品

Looking for replacement of these Magic Variable in Python

我用 magic 变量设计了这个 OOPs 代码实际上它感觉有点复杂所以我想在不使用 Magic variable.Below 代码是 Inheritance in Python.

我正处于 OOP 概念的学习阶段,请建议我最好的 OOP 实践,以及从程序员工作的角度来看,哪些概念在 OOP 中很重要。

 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()

输出

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

欢迎使用 OOP。您的代码看起来也很复杂,因为您没有遵循 python 约定。以下是一些必要的阅读材料:

对于更 Pythonic 的代码:PEP 20。 最后但同样重要的是,避免常见的陷阱:Anti-patterns

在您的代码中,您可以将 tostring 替换为 __repr__ 方法。这允许做 print(Car())。同样在 python 中,您不需要 getter 和 setter,因为没有 public 或私有变量。所以只在你的 __init__ 中定义:self.model。您将能够做到:

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