Python类内列表存储的实例方法调用提示缺少self参数怎么解决?
报错原因
你定义的instructions是类属性,定义阶段直接引用的add、beq是未绑定实例的原始函数对象,不是和具体实例绑定的方法。Python中只有通过实例.方法名的形式访问方法时,才会自动把实例作为self参数传入方法,你直接调用类属性里存储的原始函数,没有传入self参数,就会触发缺少位置参数的报错。
解决方法
下面是三种常用的可行方案:
- 方案1:将方法列表改为实例属性,在
__init__初始化阶段绑定当前实例,是最推荐的通用方案
class cpu: def __init__(self): # 初始化时绑定当前实例的方法,自动携带self self.instructions = [self.add, self.beq] def execute(self): self.instructions[0]() def add(self): print("instr add") def beq(self): print("instr beq") cpu_ = cpu() cpu_.execute()
- 方案2:调用方法时手动传入
self参数,适合需要保留instructions为类属性共享的场景
只需要修改execute方法的调用逻辑即可:
def execute(self): # 手动给原始函数传入当前实例作为self self.instructions[0](self)
- 方案3:将指令方法改为静态方法,适合方法本身不需要访问实例任何属性、方法的场景
class cpu: def __init__(self): pass def execute(self): self.instructions[0]() @staticmethod def add(): print("instr add") @staticmethod def beq(): print("instr beq") instructions = [add, beq] cpu_ = cpu() cpu_.execute()
内容的提问来源于stack exchange,提问作者Chen Chang
相关产品推荐
相关产品推荐

