python - 无法在类内的列表中执行函数
问题描述
我正在尝试在 Python 中创建函数列表。虽然我的代码可以“看到”该函数并尝试执行它,但它会遇到错误,指出它缺少位置参数self
。
class cpu:
def __init__(self):
pass
def execute(self):
self.instructions[0]()
def add(self):
print("instr add")
def beq(self):
print("instr beq")
instructions = [add, beq]
cpu_ = cpu()
cpu_.execute()
输出:
Traceback (most recent call last):
File "C:\...\src\error.py", line 17, in <module>
cpu_.execute()
File "C:\...\src\error.py", line 6, in execute
self.instructions[0]()
TypeError: add() missing 1 required positional argument: 'self'
解决方案
mikey 的回答是正确的,但让我们解释一下原因。
正如回溯所说,add
需要一个论点self
。因此,每当您调用 时add
,您至少需要传递一个参数。
在 python 中,这是由解释器在大多数典型情况下“在地毯下”完成的。当你在一个类中调用一个类方法时,你会:
self.execute()
或者当您从类实例调用方法时:
cpu_.execute()
在后台,解释器使用self
或cpu_
实例作为execute
方法的第一个参数。
换句话说,cpu_.execute()
是 的语法糖cpu.execute(cpu_)
,您从类对象调用方法并将类的实例作为第一个参数传递。
现在,当你这样做时:
def execute(self):
self.instructions[0]()
在这里您调用的是 中提到的方法instruction[0]
,但是由于该方法是在列表中定义的,因此您不能使用语法糖。点之前没有self
。当然,有self
before instructions
,但是那个是指instructions
列表,而不是列表的内容。
所以你必须明确地提供self
论点。
self.instructions[0](self)
推荐阅读
- spring-boot - 如何在模块的 Spring Boot 配置类中使用 @AutoConfigureOrder
- c# - 如何使用 MIP SDK 应用水印(Microsoft 信息保护)
- jenkins - Jenkins服务器启动问题
- angular - Firestore 组查询不起作用权限被拒绝
- javascript - Gatsby 模式弃用警告:推断的解析器
- python - 我怎样才能弄清楚为什么我的 Jupyter 内核会死掉?
- typescript - “引用一个值,但在此处用作类型”仅在导出接口时出错
- c# - 如何在不使用 Visual Studio 的情况下将测试方法与 Azure 测试计划测试用例相关联?
- angular - 如何在离子页面上触发 ngOnInit
- android - 我如何在多段线中显示路径与谷歌地图颤动的多个坐标