无法在类内的列表中执行函数

2024-05-16 09:49:22 发布

您现在位置: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'

Tags: 函数pyselfsrcaddexecutedefline
2条回答
    ...
    self.instructions[0](self)
    ...

这似乎奏效了。我不太清楚为什么

mikey's answer是正确的,但让我们解释一下原因

正如回溯所说,add需要一个参数self。因此,无论何时调用add,都需要至少传递一个参数

在python中,这是在大多数典型情况下由解释器“秘密”完成的。在类内调用类方法时,您会执行以下操作:

self.execute()

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

cpu_.execute()

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

现在,当您这样做时:

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

这里您正在调用instruction[0]中引用的方法,但是由于该方法是在列表中定义的,因此不能使用语法糖。点前面没有self。当然,在instructions之前有self,但那是指instructions列表,而不是列表的内容。
因此必须显式地提供self参数

self.instructions[0](self)

相关问题 更多 >