Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically create properties in Python?

Tags:

python

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!

like image 877
Michael Avatar asked Jun 10 '12 09:06

Michael


People also ask

How do you add properties in Python?

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.

How do you create a dynamic object in Python?

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.

What is dynamic attribute in Python?

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.

What does __ add __ do 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.


1 Answers

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))
like image 118
ThiefMaster Avatar answered Oct 21 '22 02:10

ThiefMaster