Python内部类

时间:2018-01-28 06:56:21

标签: python

我想使用内部类创建一个对象车,这个对象车有像座位数,颜色,年份,引擎等属性。最后一个属性引擎容量将具有另一个属性,如阀门数量,燃料类型,单位为kms。

所以我首先创建一个类汽车,然后创建引擎类:

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'

我想访问另一个类中的类,如下所示:

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

可以帮我解决这个问题。

此致

我重新创建对象如下:

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')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __init__
TypeError: 'str' object is not callable

1 个答案:

答案 0 :(得分:2)

您需要首先构建引擎,然后构建car

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

现在您可以访问my_car.engine.lts,例如。