Reputation: 1047
I know high order functions and closure that is created with function returns. In most of the cases I find it useful and use it repetitively. My question here is related to the closure that is created with class definition and referencing a class instance's function that is returned from a function call. Can this be categorized as regular closure or is it something else in the Python (or programming) literature? Here is an example:
class Klass:
def __init__(self, val):
self.val = val
def ret_val(self):
return self.val
def gen_val_fn(val):
inst = Klass(val)
return inst.ret_val
fn5 = gen_val_fn(5)
fn6 = gen_val_fn(6)
print("first: {}".format(fn5()))
print("second: {}".format(fn6()))
How does the internals work here? My assumption here is after gen_val_fn(5)
call, the first instance of Klass is created and it is not garbage collected until the fn5
is garbage collected. So it is able to be able to create val=5
as closure (I am not sure this can be the right terminology). Is there any document or internal knowledge that you can point out on this? Or explain it if this explanation has flaws.
Thanks!
Upvotes: 3
Views: 2810
Reputation: 19362
That is called a bound method.
A bound method holds reference to the instance (i.e. self
) and the function, so when it is called, the self
is inserted into the list of arguments.
The self
then, of course holds references to all other member variables.
In your example, try this:
>>> fn5
<bound method Klass.ret_val of <__main__.Klass object at 0x006B1270>>
>>> fn5.__self__
<__main__.Klass object at 0x006B1270>
>>> fn5.__self__.val
5
Then, calling fn5()
is the same as calling fn5.__func__(fn5.__self__)
.
Upvotes: 4