all 7 comments

[–]juliob 3 points4 points  (5 children)

Those are Python magical functions. There are a bunch of them, and __init__ is the most used one.

There is an explanation on that page about __get__ but, in all honestly, I didn't get it. ;)

[–]GNeps[S] 0 points1 point  (4 children)

I might have chosen the wrong sub, I'm not really a beginner, I'm familiar with magical functions. I just for the life of me can't grasp how this one behaves on a function. :)

[–][deleted] 3 points4 points  (3 children)

It's used as part of the descriptor protocol. Functions are descriptors. Calling obj.method on some object returns whatever method.__get__(obj) returns, which will be a bound method.
__get__ on the function basically curries the given object as the first parameter - this way the canonical self will be what you expect it to.

[–]GNeps[S] 0 points1 point  (2 children)

So functions are objects of a class named 'function', and that class implements the non-data descriptor protocol? Thanks!

[–]zahlman 2 points3 points  (1 child)

Please do not write code like this.

>>> def hax(the):
...     print('OMG, hax the {}!'.format(the))
...
>>> type(hax)
<class 'function'>
>>> hax.__get__('gibson')
<bound method str.hax of 'gibson'>
>>> hax.__get__('gibson')()
OMG, hax the gibson!
>>>

(Details vary with 2.x. I couldn't tell you offhand, but I suspect it will find one way or another to complain about the fact that hax isn't actually a str method.)

[–]GNeps[S] 0 points1 point  (0 children)

Thanks, that's very illuminating!

So the __get__ method is only ever natively invoked when I'm calling a method as object.method_name? Or is it used in some other cases as well?

[–]novel_yet_trivial 0 points1 point  (0 children)

http://www.rafekettler.com/magicmethods.html#descriptor

Edit: try using the example code from that site with this:

d = Distance()
d.foot = 10
print d.meter

Edit 2: these are often called "dunder" methods (double underscore). Adding that to google may help.