- Mastering Objectoriented Python
- Steven F. Lott
- 340字
- 2021-11-12 16:25:11
Basic attribute processing
By default, any class we create will permit the following four behaviors with respect to attributes:
- To create a new attribute by setting 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'
We can add, change, and remove 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 using an instance of the class 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 object. Any attempt to use an undefined attribute raises an exception. A SimpleNamespace
class has different behavior from what we saw when we created an instance of the object class.. A simple instance of the object class doesn't permit the creation of new attributes; it lacks the internal __dict__
structure that Python stores attributes and values in.