|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- from class_examples1 import Car
- class ElectricCar(Car):
- def __init__(self, make, model, year):
- super().__init__(make, model, year)
- self.battery = Battery
- class Battery:
- def __init__(self, battery_size=70):
- self.battery_size = battery_size
- def describe_battery(self):
- print('This car has a ' + str(self.battery_size) + '-kWh battery')
- my_tesla = ElectricCar('tesla', 'model s', 2016)
- print(my_tesla.get_descriptive_name())
- my_tesla.battery().describe_battery()
复制代码
这里的20行中my_tesla.battery().describe_battery()的,my_tesla.battery后边为什么需要加括号,如果是my_tesla.battery.describe_battery()则会报错,请问这是为什么?
因为在类中定义的方法默认是实例方法,实例方法只有实例调用才会自动传入 self,
而 battery 你赋值为了 Battery 类,还没有实例化,
你可以把代码改成这样:
- from class_examples1 import Car
- class ElectricCar(Car):
- def __init__(self, make, model, year):
- super().__init__(make, model, year)
- self.battery = Battery() # 这里加括号,后面就不用加括号
- class Battery:
- def __init__(self, battery_size=70):
- self.battery_size = battery_size
- def describe_battery(self):
- print('This car has a ' + str(self.battery_size) + '-kWh battery')
- my_tesla = ElectricCar('tesla', 'model s', 2016)
- print(my_tesla.get_descriptive_name())
- my_tesla.battery.describe_battery() # 这里不加括号
复制代码
|
|