>>> 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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With