即使提供也缺少可调用参数

Missing callable argument even if provided

鉴于以下情况:

from dataclasses import dataclass
from typing import Callable

class Bar:
    def bar_meth():
        return [1, 2, 3]

class Foo(Bar):
    @staticmethod
    def foo_meth(a: int, b: int, base_func: Callable, *args):
        # sample code, it doesn't really matter as I'm sure this part works
        items = []
        for x in range(a, b):
            items.extend(base_func(args))

        return items

@dataclass
class Source:
    call: Callable = None
    args: tuple = None
    kwargs: dict = None

    def run(self):
        return self.call(self.args, self.kwargs)

class Binder:
    def __init__(self):
        self.source = Source()

    def bind(self, source: Callable, *args, **kwargs):
        self.source = Source(source, args, kwargs)

        return self.source

    def check(self):
        return self.source.run()
# main.py
a = Foo()
b = Binder()

b.bind(a.foo_meth, 0, 50, a.bar_meth)
b.check()

所有这些混乱在 return self._call(self._args, self._kwargs) 引发了 TypeError: foo_meth() missing 1 required positional argument: 'base_func'。 我检查了调试器和 b.args = (arg1, arg2, <bound method Bar.bar_meth of <object and 0xAddress>>),所以 bar_meth() 应该正确传递。

我知道这看起来很复杂,但我不知道如何改进它,所以如果您没有解决方案,也许您可​​以提供一些返工建议。

当您在 Source.run() 中执行 self.call() 时,您需要 解压 self.argsself.kwargs

将函数更改为:

def run(self):
    return self.call(*self.args, **self.kwargs)

看来您也忘记了在 Foo.foo_meth()

中解压 base_func() 的参数
def foo_meth(a: int, b: int, base_func: Callable, *args):
        # sample code, it doesn't really matter as I'm sure this part works
        items = []
        for x in range(a, b):
            items.extend(base_func(*args)) # <<------ Unpack here too

        return items

现在你的 MRE 给出了不同的错误 --

TypeError: bar_meth() takes 0 positional arguments but 1 was given

这是因为您定义 Bar.bar_meth() 时没有任何参数,但您将其称为 a.bar_meth(args)。您需要将其重新定义为

class Bar:
    def bar_meth(self):
        return [1, 2, 3]