How do I dynamically create properties in Python? -
suppose have class this:
class alphabet(object): __init__(self): self.__dict = {'a': 1, 'b': 2, ... 'z': 26} @property def a(self): return self.__dict['a'] @property def b(self): return self.__dict['b'] ... @property def z(self) return self.__dict['z']
this long , cumbersome task define , seems highly redundant. there way dynamically create these properties? know can dynamically create attributes built-in setattr, want have control on read/write/delete access (for reason want use property). thanks!
don't use properties implement following methods:
__getattr__(self, name)
__setattr__(self, name, value)
__delattr__(self, name)
see http://docs.python.org/reference/datamodel.html#customizing-attribute-access
your __getattr__
method this:
def __getattr__(self, name): try: return self.__dict[name] except keyerror: msg = "'{0}' object has no attribute '{1}'" raise attributeerror(msg.format(type(self).__name__, name))
Comments
Post a Comment