The names inside the instance are called attributes. (The methods are technically attributes—attributes that are of type function.) There are three operations on attributes: get, set, and delete.
To get an attribute means
to retrieve its value. Python searches the
instance's .__dict__ for the
attribute's name; if that name is found, its value
is returned. If the instance's .__dict__ does not have a binding for the
given name, Python searches the class's .__dict__. If no value is found there,
Python searches the namespaces of the ancestor
classes (if any).
>>> class C: ... def __init__(self, x): ... self.thingy = x ... >>> c=C(42) >>> c.thingy 42 >>> c.__dict__['thingy'] 42
When you call a method of an instance M in an
expression of the form “I”, this is considered just
another attribute “get” operation:
the get operation I.M(...) retrieves the method, and then that
method is called using the arguments inside the
“I.M(...)”.
To set an attribute means
to give it a value. If there is an existing
attribute with the same name, its old value is
discarded, and the attribute name is bound to the
new value. The new value is stored in the
instance's .__dict__.
>>> c.thingy 42 >>> c.thingy = 58 >>> c.thingy 58 >>> c.__dict__['thingy'] 58
You can delete an
attribute from an instance using a del statement (see Section 22.3, “The del statement: Delete a name or part
of a value”).
>>> c.thingy 58 >>> del c.thingy >>> c.thingy Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: C instance has no attribute 'thingy'
In addition to ordinary attributes and methods,
your class can accept references to names that do
not exist in the instance
or class namespace. You can define special
methods that will be called when some statement
tries to get, set, or delete an attribute that
isn't found in the instance's .__dict__. See Section 26.3.14, “__getattr__(): Handle a reference
to an unknown attribute”, Section 26.3.21, “__setattr__(): Intercept all
attribute changes”, and Section 26.3.9, “__delattr__(): Delete an
attribute”.
If all else fails—if an attribute is not found
in the instance's namespace and the class does not
provide a special method that handles the attribute
reference—Python will raise an AttributeError exception.