Created
March 25, 2017 15:53
-
-
Save brake/76836a029f9ef6ded3af3470cc22d971 to your computer and use it in GitHub Desktop.
Instance methods dynamic generation depending from __init__'s parameter, avoiding a late binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from types import MethodType | |
| def fn_factory(i, obj): | |
| """Function factory - avoids a late binding in closures""" | |
| def fn(self): | |
| return i | |
| return MethodType(fn, obj) | |
| class Aaa(object): | |
| def __init__(self, n): | |
| self.registry = {} | |
| for i in range(n): | |
| fn = fn_factory(i, self) | |
| self.registry[i] = fn | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment