讓我舉個簡單的例子:如何使用實例作爲屬性?
如果我想使用Tank
Class實例作爲汽車的屬性。同時,我想要tank_info
的方法,根據Car
類中的不同型號給出不同的坦克尺寸。
class Car():
def __init__(self, make, model):
self.make = make
self.model = model
self.tank = Tank()
def get_car_info(self):
long_name = self.make + ' ' + self.model
print('The car is', long_name)
class Tank():
def __init__(self, tank_size=20):
self.tank_size = tank_size
def tank_info(self):
print('The tank size is', self.tank_size, 'gallons')
my_car = Car('Audi', 'A4')
my_car.get_car_info()
my_car.tank.tank_info()
比方說,奧迪A4,A6和A8,他們的坦克大小20,25,30 我應該如何寫tank_info
方法,它自動告訴它有什麼槽尺寸?
你想硬編碼罐大小的不同型號或你想要的尺寸爲'汽車.__ init__'額外的參數傳遞? – MSeifert
使用字典將汽車映射到坦克大小。 – wwii