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

Python抽象类编程中‘SpecialDrive对象不可调用’错误排查

问题原因与修复方案

错误根源

在Vehicle类中,你同时定义了名为drive的实例属性和实例方法,导致实例属性覆盖了同名的类方法。

具体逻辑:

  • __init__方法里self.drive = drive将传入的SpecialDrive对象赋值给了实例属性drive
  • 后续定义的def drive(self):方法,会被实例属性覆盖(实例属性的访问优先级高于类方法)

当你调用safari.drive()时,实际是在尝试调用那个SpecialDrive对象,而该类没有实现__call__方法,因此抛出“'SpecialDrive' object is not callable”错误。

修复方案

只需要让属性名和方法名不重复即可,以下是两种可行的修改方式:

方式1:修改方法名

from abc import ABC, abstractmethod
class DriveStrategy(ABC):
    @abstractmethod
    def drive_strategy(self):
        pass
    
class NormalDrive(DriveStrategy):
    def drive_strategy(self):
        print("Normal Drive")

class SpecialDrive(DriveStrategy):
    def drive_strategy(self):
        print("Special Drive")
        
        
class Vehicle:
    def __init__(self, drive: DriveStrategy):
        self.drive = drive
    
    def perform_drive(self):
        self.drive.drive_strategy()

class SUV(Vehicle):
    def just_a_method(self):
        print("from SUV")

class PassengerBus(Vehicle):
    def bus_method(self):
        print("From Bus")

safari = SUV(SpecialDrive())
safari.perform_drive()

方式2:修改属性名

from abc import ABC, abstractmethod
class DriveStrategy(ABC):
    @abstractmethod
    def drive_strategy(self):
        pass
    
class NormalDrive(DriveStrategy):
    def drive_strategy(self):
        print("Normal Drive")

class SpecialDrive(DriveStrategy):
    def drive_strategy(self):
        print("Special Drive")
        
        
class Vehicle:
    def __init__(self, drive: DriveStrategy):
        self._drive = drive
    
    def drive(self):
        self._drive.drive_strategy()

class SUV(Vehicle):
    def just_a_method(self):
        print("from SUV")

class PassengerBus(Vehicle):
    def bus_method(self):
        print("From Bus")

safari = SUV(SpecialDrive())
safari.drive()

内容的提问来源于stack exchange,提问作者Yash Porwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 03:00:29