>> cl...">

Why do .MethodType types complain about too many arguments?

>>> 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

I'm just wondering what were the 2 arguments I gave? I know that one of them will be self, but what was the other?

Of course, in this example the correct way is:

>>> types.MethodType(Foo.say, b)()
Foo say

But I am asking for an error types.MethodType(f.say, b)(). I want to know why he complains

takes 1 positional argument, but 2 are given

+4
source share
2 answers

The correct way to do this is:

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)()

You must bind a function Foo.say.__func__ to the instance.

+1
source

In any method call, the first argument is the object itself as an implicit argument. In your case, an example

types.MethodType(f.say, b)()

translated into

f.say(b)

which further translates into

say(f, b)

so you ended up sending two arguments

+1
source

All Articles