Created
December 31, 2012 17:55
-
-
Save nakamuray/4421604 to your computer and use it in GitHub Desktop.
python で self 書かなくてもよくしてくれる君
This file contains 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
import functools | |
import inspect | |
def self(): | |
return inspect.currentframe().f_back.f_back.f_locals['self'] | |
class AutoSelfMeta(type): | |
def __new__(cls, names, bases, attrs): | |
for k, v in attrs.iteritems(): | |
if hasattr(v, '__call__') and type(v) != type: | |
attrs[k] = autoselfize(v) | |
return super(AutoSelfMeta, cls).__new__(cls, names, bases, attrs) | |
def autoselfize(method): | |
def wrapper(self, *args, **kwargs): | |
return method(*args, **kwargs) | |
return functools.update_wrapper(wrapper, method) | |
class AutoSelf(object): | |
__metaclass__ = AutoSelfMeta | |
def test(): | |
class MyClass(AutoSelf): | |
def __init__(x): | |
self().x = x | |
def print_x(): | |
print self().x | |
o = MyClass(100) | |
o.print_x() | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment