Created
September 14, 2012 22:32
-
-
Save showell/3725366 to your computer and use it in GitHub Desktop.
silly example that shows how python classes are really just sugar for the simple cases
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
def Blank(): | |
# this is a hacky way of returning an empty | |
# object that you can set attributes on, without | |
# having to create a class | |
return lambda: None | |
def klass(factory): | |
def init(*args): | |
self = Blank() | |
def method(method_name): | |
def decorate(f): | |
setattr(self, method_name, f) | |
return f | |
return decorate | |
return factory(self, method, *args) | |
return init | |
@klass | |
def Person(self, method, name, salary): | |
self.name = name | |
self.salary = salary | |
@method('give_raise') | |
def _(): | |
self.salary *= 1.1 | |
return self | |
alice = Person('alice', 100) | |
bob = Person('bob', 200) | |
print alice.name | |
alice.give_raise() | |
print alice.salary | |
print bob.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment