为何创建子类后,在PyCharm中无法调用指定函数?
问题原因与解决办法
核心原因
你犯了两个关键错误:
- 你将
Tesla实例化为**Car类对象**,但Car类本身并没有upgrade_battery方法——这个方法属于Battery类,只有ElectricCar子类的实例才会绑定battery属性。 - 就算实例化为
ElectricCar,upgrade_battery也不是ElectricCar的直接方法,必须通过实例的battery属性去调用。
修正步骤
- 替换实例化类:把
Tesla = Car("Telsa", "Cybertruck", "2024")改成Tesla = ElectricCar("Tesla", "Cybertruck", 2024)(注意修正拼写错误"Telsa",年份用整数更符合逻辑)。 - 正确调用方法:通过
battery属性调用方法,即Tesla.battery.upgrade_battery()。
修正后的完整代码
class Car: """A simple attempt to represent a car.""" def __init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage.""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self, mileage): """Set the odometer reading to the given value.""" if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """Add the given amount to the odometer reading.""" self.odometer_reading += miles class Battery: def __init__(self, battery_size=40): """Initialize the battery's attributes.""" self.battery_size = battery_size def describe_battery(self): """Print a statement describing the battery size.""" print(f"This car has a {self.battery_size}-kWh battery.") def get_range(self): """Print a statement about the range this battery provides.""" if self.battery_size == 40: range_val = 150 elif self.battery_size == 65: range_val = 225 print(f"This car can go about {range_val} miles on a full charge.") def upgrade_battery(self): """Upgrade the battery if possible.""" if self.battery_size == 40: self.battery_size = 65 print("Upgraded the battery to 65 kWh.") else: print("The battery is already upgraded.") class ElectricCar(Car): """Represent aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """ Initialize attributes of the parent class. Then initialize attributes specific to an electric car. """ super().__init__(make, model, year) self.battery = Battery() # 修正实例化与方法调用 Tesla = ElectricCar("Tesla", "Cybertruck", 2024) Tesla.battery.upgrade_battery()
内容的提问来源于stack exchange,提问作者The Code
相关产品推荐
相关产品推荐

