对于那些需要上下文的人,我正在研究Python Crash课程,第176页。
对于最后一行代码,为什么我可以在my_tesla.battery.describe_battery()
之前键入self.
而没有battery
?
class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer = 20000
def get_description(self):
"""This function gives a full name of the cars make, model and year and returns it to the function."""
long_name = str(self.year) + " " + self.make + " " + self.model
return long_name.title()
def odometer_reading(self):
"""This function prints the odometer reading of the vehicle."""
return self.odometer
def update_mileage(self, mileage):
if mileage >= self.odometer:
self.odometer = mileage
else:
print("You can not roll back the odometer!")
def increase_mileage(self, mile):
self.odometer += mile
return self.odometer
class Battery():
"""This creates the classes __init__ method and sets a default battery_size to 70"""
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.")
class ElectricCar(Car):
"""Initializes the parents class - Car() into the child class - ElectricCar()."""
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()
my_tesla=ElectricCar('tesla','model s', 2016)
print(my_tesla.get_description())
my_tesla.battery.describe_battery()`
我希望输入:
my_tesla.self.battery.describe_battery()
,以允许使用属性battery
。