Basic attribute processing

By default, any class we create will permit the following four behaviors with respect to attributes:

  • To create a new attribute and set its value
  • To set the value of an existing attribute
  • To get the value of an attribute
  • To delete an attribute

We can experiment with this using something as simple as the following code. We can create a simple, generic class and an object of that class:

>>> class Generic: 
...     pass 
...      
>>> g = Generic() 

The preceding code permits us to create, get, set, and delete attributes. We can easily create and get an attribute. The following are some examples:

>>> g.attribute = "value" 
>>> g.attribute 
'value' 
>>> g.unset 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'Generic' object has no attribute 'unset' 
>>> del g.attribute 
>>> g.attribute 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'Generic' object has no attribute 'attribute' 

The example shows adding, changing, and removing attributes. We will get exceptions if we try to get an otherwise unset attribute or delete an attribute that doesn't exist yet.

A slightly better way to do this is to use an instance of the types.SimpleNamespace class. The feature set is the same, but we don't need to create an extra class definition. We create an object of the SimpleNamespace class instead, as follows:

>>> import types 
>>> n = types.SimpleNamespace() 

In the following code, we can see that the same use cases work for a SimpleNamespace class:

>>> n.attribute = "value" 
>>> n.attribute 
'value' 
>>> del n.attribute 
>>> n.attribute 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'namespace' object has no attribute 'attribute' 

We can create attributes for this instance, n. Any attempt to use an undefined attribute raises an exception.

An instance of the SimpleNamespace class has different behavior from what we saw when we created an instance of the object class. An instance of the object class doesn't permit the creation of new attributes; it lacks the internal __dict__ structure that Python uses to store attributes and values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset