Lost in descriptor land
Steven D'Aprano
steve at pearwood.info
Sun Jul 3 11:32:43 EDT 2016
On Sun, 3 Jul 2016 09:06 am, Ian Kelly wrote:
> you can't define a method
> on an instance (though you can certainly store a function there and
> call it).
Yes -- the difference is that Python doesn't apply the descriptor protocol
to attributes attached to the instance. So the function remains a function
and is not converted to a method, which means it doesn't automatically get
the special "self" argument:
class Test(object):
pass
instance = Test()
def method(self):
print("method called from self", self)
instance.method = method
If you try to call the "method", you get an error:
py> instance.method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() missing 1 required positional argument: 'self'
But if you prepare the method ahead of time, it works:
from types import MethodType
instance.method = MethodType(method, instance)
Now calling it works fine:
py> instance.method()
method called from self <__main__.Test object at 0xb79fcf14>
--
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list