Suppose I have a python class Car, and, as part of Car I want to have classes Engine and Exhaust. Engine and Exhaust will both depend on a number of the attributes of Car, and both will have some attributes and methods which are unique to themselves. Engine and Exhaust will only ever be used inside the definition of Car.
In this situation, I have usually coded Exhaust and Engine as separate classes, passing the required attributes of Car explicitly when I create them:
class Engine:
def __init__(self,numCylinders):
self.numCylinders=kwargs[“numCylinders”]
self.engineTemp=0
class Exhaust:
def __init__(self, maxEmission):
self.maxEmissions=MaxEmission
self.currentEmission=0
class Car:
def __init__(self,**kwargs):
self.numDoors=kwargs[“numDoors”]
self.mpg=kwargs[“mpg”]
self.numCylinders=kwargs [“numCylinders”]
self.maxEmissions=kwargs[“maxEmissions”]
(More stuff)
self.engine=Engine(self.numCylinders)
self.exhaust=Exhaust(self.maxEmissions)`
I would like to have a more efficient way for Engine and Exhaust to inherit from Car. However, I don’t think I want Engine and and Exhaust to be subclasses of Car; the definition of Car depends on the existence of Engine and Exhaust, so I don’t see how that would work. Is there a better way than what I am doing?
The problem with the above approach is that it the construction of the helper classes can become very cumbersome when you have tons of parameters to pass in.
Aucun commentaire:
Enregistrer un commentaire