arjunaskykok
arjunaskykok

Reputation: 956

Why does types.MethodType complain 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 am just wondering what were 2 arguments that I gave? I know one of them would be self, but what was the other one?

Of course, in this example, the correct way would be:

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

But I am asking about the error of types.MethodType(f.say, b)(). I want to know why it complains

takes 1 positional argument but 2 were given

Upvotes: 5

Views: 948

Answers (2)

James Mills
James Mills

Reputation: 19050

The correct way of doing 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 have to bind the function Foo.say.__func__ to an instance.

Upvotes: 2

Abhijit
Abhijit

Reputation: 63767

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

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

translated to

f.say(b)

which further translates to

say(f, b)

so eventually you ended up sending two arguments

Upvotes: 2

Related Questions