mlopez2305
mlopez2305

Reputation: 9

Python inner classes

I want to create an object car using inner classes, this object car have attributes like number of seats, color, year, engine. The last attribute engine capacity will have another attributes like number of valves, type of fuel, kms by lts.

so I am creating a class car first and then engine class:

class car:
     def __init__(self, color, year, engine):
        self.color = color
        self.year = year
        self.engine = engine

class engine:
    def __init__(lts, kms_by_lts, fuel_type, valves ):
        self.lts = lts
        self.fuel = fuel
        self.valves = valves
        self.kms_by_lts = kms_by_lts

>> my_car = car('blue','2010','v6')
>>> my_car.engine
'v6'

I want to access a class inside another class like as follow:

>>> my_car.v6.lts = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: car instance has no attribute 'v6'

Could help me with this issue.

Regards

I recreate the object as follow:

class car:
     def __init__(self, color, year, engine):
        self.color = color
        self.year = year
        self.engine = engine()

class engine:
    def __init__(lts, kms_by_lts, fuel_type, valves ):
        self.lts = lts
        self.fuel = fuel
        self.valves = valves
        self.kms_by_lts = kms_by_lts

Having the following error

>>> my_car = car('blue','2010','v6')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __init__
TypeError: 'str' object is not callable

Upvotes: 0

Views: 129

Answers (1)

John Zwinck
John Zwinck

Reputation: 249502

You need to construct an engine first, then a car:

my_engine = engine(8.4, 5.5, 'petrol', 20)
my_car = car('blue', '2010', my_engine)

Now you can access my_car.engine.lts, for example.

Upvotes: 2

Related Questions