Last active
December 16, 2015 21:09
-
-
Save viniciusban/5497532 to your computer and use it in GitHub Desktop.
Make a function be a new member of an instance object
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
# create the tables | |
db.define_table('person', | |
Field('name'), | |
Field('gender'), | |
Field('birthdate', 'date')) | |
db.define_table('animal', | |
Field('name'), | |
Field('gender'), | |
Field('birthdate', 'date')) | |
# Bind the function to tables. | |
# Note the use of "self". | |
# Due to this decorator, we're "inside" the instance. | |
@make_member_of(db.person, 'just_men') | |
@make_member_of(db.animal, 'just_males') | |
def get_just_gender_equals_m(self): | |
return self._db(self.gender == 'm').select() | |
# Use the function as a regular table method. | |
db.person.just_men() | |
db.animal.just_males() |
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
# Create the decorator function | |
def make_member_of(instance, method_name=None): | |
def _decorated(f): | |
import types | |
f2 = types.MethodType(f, instance, instance.__class__) | |
_name = method_name or f.func_name | |
setattr(instance, _name, f2) | |
return f | |
return _decorated | |
# note: this must be defined before binding functions to instance. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment