为什么 types.MethodType 抱怨太多参数?

arj*_*kok 5 python

>>> import types
>>> class Foo:
...   def say(self):
...     print("Foo say")
... 
>>> class Bar:
...   def say(self):
...     print("Bar say")
... 
>>> f = Foo()
>>> b = Bar()
>>> types.MethodType(f.say, b)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: say() takes 1 positional argument but 2 were given
Run Code Online (Sandbox Code Playgroud)

我只是想知道我给出的 2 个参数是什么?我知道其中一个是self,但另一个是什么?

当然,在这个例子中,正确的方法是:

>>> types.MethodType(Foo.say, b)()
Foo say
Run Code Online (Sandbox Code Playgroud)

但我问的是types.MethodType(f.say, b)(). 我想知道为什么它会抱怨

需要 1 个位置参数,但给出了 2 个

Jam*_*lls 2

正确的做法是:

import types


class Foo:

    def say(self):
        print("Foo say")


class Bar:

    def say(self):
        print("Bar say")

f = Foo()
b = Bar()
types.MethodType(Foo.say.__func__, b)()
Run Code Online (Sandbox Code Playgroud)

您必须将该函数绑定一个实例。 Foo.say.__func__