首页 > 解决方案 > 无法在类内的列表中执行函数

问题描述

我正在尝试在 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'

标签: python

解决方案


mikey 的回答是正确的,但让我们解释一下原因。

正如回溯所说,add需要一个论点self。因此,每当您调用 时add,您至少需要传递一个参数。

在 python 中,这是由解释器在大多数典型情况下“在地毯下”完成的。当你在一个类中调用一个类方法时,你会:

self.execute()

或者当您从类实例调用方法时:

cpu_.execute()

在后台,解释器使用selfcpu_实例作为execute方法的第一个参数。
换句话说,cpu_.execute()是 的语法糖cpu.execute(cpu_),您从类对象调用方法并将类的实例作为第一个参数传递。

现在,当你这样做时:

def execute(self):
    self.instructions[0]()

在这里您调用的是 中提到的方法instruction[0],但是由于该方法是在列表中定义的,因此您不能使用语法糖。点之前没有self。当然,有selfbefore instructions,但是那个是指instructions列表,而不是列表的内容。
所以你必须明确地提供self论点。

self.instructions[0](self)

推荐阅读