- Daniel Arbuckle's Mastering Python
- Daniel Arbuckle
- 223字
- 2025-04-04 18:57:48
Attributes
We discussed a little while ago that we could add attributes to function objects, which is often handy. We could do something similar with classes, with one big difference- attributes that we add to functions are only visible to the code that has access to that function object, which usually doesn't include the code of the function itself, but attributes that we add to class objects are visible to any code that has access to the class object or to an object of the type described by the class.
This means that if we add an attribute to a class, the functions defined in that class will be able to access that attribute through the self parameter, as shown in the following code example:

We need to be careful when adding attributes to classes because if we accidentally overwrite one of the class' attributes, we could break the class.
We have a greater ability to manipulate classes than functions. So, we need to use that ability more thoughtfully. Also, notice that, in this example, one of the attributes we added to the class is a function, which then proceeded to work exactly as if it had been defined as a part of the class from the beginning.
Next, let's take a short tour of some of the highlights of Python's standard library.