Skip to content

Instantly share code, notes, and snippets.

@nakamuray
Created December 31, 2012 17:55
Show Gist options
  • Save nakamuray/4421604 to your computer and use it in GitHub Desktop.
Save nakamuray/4421604 to your computer and use it in GitHub Desktop.
python で self 書かなくてもよくしてくれる君
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