Created
November 12, 2009 15:15
-
-
Save sneeu/232969 to your computer and use it in GitHub Desktop.
Bracketless function calls (a la Ruby) in Python.
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 Bracketless(object): | |
def __getattribute__(self, name): | |
try: | |
attr = object.__getattribute__(self, name) | |
if callable(attr): | |
args, __, __, __ = inspect.getargspec(attr) | |
if len(args) == 1: # 1 for `self` | |
return attr() | |
return attr | |
except Exception, e: | |
raise e | |
raise AttributeError | |
def method(self, name): | |
return object.__getattribute__(self, name) | |
class Person(Bracketless): | |
def __init__(self, forename, surname): | |
self.forename = forename | |
self.surname = surname | |
def full_name(self): | |
print 'Python can be *just like Ruby*.' | |
return '%s %s' % (self.forename, self.surname, ) | |
if __name__ == '__main__': | |
guido = Person('Guido', 'van Rossum') | |
print guido.full_name | |
print guido.method('full_name') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment