Created
July 22, 2013 20:22
-
-
Save nosamanuel/6057314 to your computer and use it in GitHub Desktop.
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
| import inspect | |
| class Selfless(type): | |
| def __new__(cls, name, bases, attrs): | |
| # Detect any methods without `self` as the first argument | |
| selfless_methods = {} | |
| for k, v in attrs.items(): | |
| if callable(v): | |
| try: | |
| args, vargs, kwargs, defaults = inspect.getargspec(v) | |
| if not args or args[0] != 'self': | |
| selfless_methods[k] = attrs.pop(k) | |
| except TypeError: | |
| continue | |
| # Inject `self` as the first argument to selfless methods | |
| def selfless(g): | |
| return lambda self, *args, **kwargs: g(*args, **kwargs) | |
| # Set selfless methods as wrapped attributes | |
| new_class = type(name, bases, attrs) | |
| for k, f in selfless_methods.items(): | |
| import ipdb; ipdb.set_trace() | |
| setattr(new_class, k, selfless(f)) | |
| return new_class | |
| class HelloWorld(object): | |
| __metaclass__ = Selfless | |
| def __init__(self, name): | |
| self.name = name | |
| def say_hello(self): | |
| print 'Hello, {}!'.format(self.name) | |
| def say_hello_world(): | |
| print 'Hello, World!' | |
| def say_hello_to(name): | |
| print 'Hello, {}!'.format(name) | |
| if __name__ == '__main__': | |
| hello = HelloWorld(name='Noah') | |
| hello.say_hello() | |
| hello.say_hello_world() | |
| hello.say_hello_to('Travis') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment