Python子类if-else分支异常排查:调用battery_size('faraday')失败原因
ecar1.battery_size('faraday') Fails Let's break down exactly what's going wrong in your ElectricCar class's battery_size method—there are two critical bugs in the else branch that cause the failure:
Uninitialized
self.batteryattribute
In the'e'and'x'cases, you explicitly setself.battery = 70andself.battery = 90respectively. But when the model is 'faraday' (triggering theelseblock), you never assign a value toself.battery. When the code reaches the print statement at the end, it tries to accessself.battery, which doesn't exist yet—this immediately throws anAttributeError.Overwriting the
battery_sizemethod itself
To make things worse, in theelseblock you wroteself.battery_size = 80. This replaces the instance'sbattery_sizemethod (the very method you're currently executing!) with an integer value of 80. Even if you fixed theself.batteryissue, any future calls toecar1.battery_size()would fail because now it's an integer, not a callable method.
Fix the Code
To resolve both problems, simply correct the else branch to set self.battery instead of self.battery_size:
class ElectricCar(Car): def __init__(self, company_name, year, model_name): super().__init__(company_name, year, model_name) def battery_size(self, model): if model == 'e': self.model_name = model self.battery = 70 elif model == 'x': self.model_name = model self.battery = 90 else: self.model_name = model self.battery = 80 # Fixed this line! print(f"Model {self.model_name.title()} has {self.battery}kWh battery")
With this fix, calling ecar1.battery_size('faraday') will correctly initialize self.battery to 80 and print the expected message without errors.
内容的提问来源于stack exchange,提问作者Neeraj Lagwankar

