You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python子类if-else分支异常排查:调用battery_size('faraday')失败原因

Why 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:

  1. Uninitialized self.battery attribute
    In the 'e' and 'x' cases, you explicitly set self.battery = 70 and self.battery = 90 respectively. But when the model is 'faraday' (triggering the else block), you never assign a value to self.battery. When the code reaches the print statement at the end, it tries to access self.battery, which doesn't exist yet—this immediately throws an AttributeError.

  2. Overwriting the battery_size method itself
    To make things worse, in the else block you wrote self.battery_size = 80. This replaces the instance's battery_size method (the very method you're currently executing!) with an integer value of 80. Even if you fixed the self.battery issue, any future calls to ecar1.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:17:44