Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Dynamic function creation in Metaclass
- class MetaClass(type):
- def __init__(cls, name, bases, attrs):
- print "Defining class : %s" % (cls,)
- ra = [(key, value) for key, value in cls.__dict__.items() if not key.startswith('_')]
- for (k, v) in ra:
- setattr(cls, "_"+k, v)
- def get_a(cls):
- print "Getting value of " + k
- get_a(cls)
- get_a.__name__ = "get_" + k
- get_a.__doc__ = "Documentation for get_" + k
- setattr(cls,get_a.__name__, get_a)
- print get_a.__name__, get_a.__doc__
- class BaseObject(object):
- __metaclass__ = MetaClass
- pass
- class Pers(BaseObject):
- nom = "Toune"
- prenom = "Fabien"
- p = Pers()
- def get_a(cls):
- print "Getting value of " + k
- def get_a(cls, k=k):
- print "Getting value of " + k
- for (k, v) in ra:
- setattr(cls, "_"+k, v)
- def new_method(val):
- def inner_get_a(cls):
- print "Getting value of " + val
- return inner_get_a
- get_a = new_method(k)
- get_a(cls)
- get_a.__name__ = "get_" + k
- get_a.__doc__ = "Documentation for get_" + k
- setattr(cls,get_a.__name__, get_a)
- print get_a.__name__, get_a.__doc__
Advertisement
Add Comment
Please, Sign In to add comment