Guest User

Untitled

a guest
May 22nd, 2012
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. Dynamic function creation in Metaclass
  2. class MetaClass(type):
  3. def __init__(cls, name, bases, attrs):
  4. print "Defining class : %s" % (cls,)
  5. ra = [(key, value) for key, value in cls.__dict__.items() if not key.startswith('_')]
  6. for (k, v) in ra:
  7. setattr(cls, "_"+k, v)
  8. def get_a(cls):
  9. print "Getting value of " + k
  10. get_a(cls)
  11. get_a.__name__ = "get_" + k
  12. get_a.__doc__ = "Documentation for get_" + k
  13. setattr(cls,get_a.__name__, get_a)
  14. print get_a.__name__, get_a.__doc__
  15.  
  16. class BaseObject(object):
  17. __metaclass__ = MetaClass
  18. pass
  19.  
  20. class Pers(BaseObject):
  21. nom = "Toune"
  22. prenom = "Fabien"
  23.  
  24. p = Pers()
  25.  
  26. def get_a(cls):
  27. print "Getting value of " + k
  28.  
  29. def get_a(cls, k=k):
  30. print "Getting value of " + k
  31.  
  32. for (k, v) in ra:
  33. setattr(cls, "_"+k, v)
  34. def new_method(val):
  35. def inner_get_a(cls):
  36. print "Getting value of " + val
  37. return inner_get_a
  38. get_a = new_method(k)
  39. get_a(cls)
  40. get_a.__name__ = "get_" + k
  41. get_a.__doc__ = "Documentation for get_" + k
  42. setattr(cls,get_a.__name__, get_a)
  43. print get_a.__name__, get_a.__doc__
Advertisement
Add Comment
Please, Sign In to add comment