简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM