Suppose I have a class like 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 would be a long and cumbersome task to define and it seems highly redundant. Is there a way to dynamically create these properties? I know you can dynamically create attributes with the built-in setattr, but I want to have control over read/write/delete access (for this reason I want to use a property). Thanks!
You can create a property by calling property() with an appropriate set of arguments and assigning its return value to a class attribute. All the arguments to property() are optional. However, you typically provide at least a setter function.
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python.
__add__ magic method is used to add the attributes of the class instance. For example, let's say object1 is an instance of a class A and object2 is an instance of class B and both of these classes have an attribute called 'a', that holds an integer.
Don't use properties but implement the 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 could look like 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With