Registry of Methods via Decorators
Steven Bethard
steven.bethard at gmail.com
Thu Jun 22 10:38:27 EDT 2006
bayerj wrote:
> I want to make a registry of methods of a class during creation.
I think you're going to need a metaclass for this, e.g.::
>>> import inspect
>>> def registered(func):
... func.registered = True
... return func
...
>>> class RegisterFuncs(type):
... def __init__(cls, name, bases, classdict):
... cls.methods = []
... for name, value in classdict.iteritems():
... if inspect.isfunction(value):
... if hasattr(value, 'registered'):
... cls.methods.append(name)
...
>>> class C(object):
... __metaclass__ = RegisterFuncs
... @registered
... def first_func(self):
... pass
... @registered
... def second_func(self):
... pass
...
>>> C.methods
['first_func', 'second_func']
If you just want to store *all* method names, you can dispense with the
@registered decorator and the hasattr() check.
STeVe
More information about the Python-list
mailing list