Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does types.MethodType complain too many arguments?

Tags:

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

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

like image 258
arjunaskykok Avatar asked Oct 03 '22 04:10

arjunaskykok


2 Answers

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

like image 164
Abhijit Avatar answered Oct 13 '22 10:10

Abhijit


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.

like image 29
James Mills Avatar answered Oct 13 '22 10:10

James Mills