Implementing Class Attributes in Python Classes
2 min readJul 16, 2022
The aim of this pageš is to show how class attributes are defined and used in Python.
- tl;dr: use
<ClassName>
prefix for class attributes andself
prefix for instance attributes - Warning: there are the notes from the wonderful https://www.pluralsight.com/courses/core-python-classes-object-orientation
1. INTRO NOTES
- Class attributes pertain to the whole class, not to an instance of the class
- Class attributes are shared between all attributes of the class
2. HOW NOT TO DO THINGS #1
- throws
UnboundLocalError: local variable 'next_serial' referenced before assignment
local variable 'next_serial' referenced before assignme
- why? because the code in class block does not count as enclosing and LEGB therefore does not apply there
3. THIS IS JUST ABOUT RIGHT
- Refer to the name of the class when assigning the class attributes within the instance method
- As with the
self
prefix, using theClassName
prefix for class attributes, it confers the same understandability advantage, reducing the amount of detective work required to which objects are being referred to
- Remember the zen Python local: 00.03-Explicit-is-better-than-implicit.md
- We can access the class attribute from outside of the object, too
>>> ShippingContainer.next_serial
1340
- Or, we can access the same attribute through any of the instances
>>> c3.next_serial
1340
>>> c4.next_serial
1340
4. HOW NOT TO DO THINGS #2
- Theoretically, it is possible to refer to the class attribute also with the
self
prefix self
is instance object reference; if there is no instance attribute, interpreter looks up among class attributes<ClassName>
is class object reference- This, even though works as expected, should be avoided
- There are āconflicting interestsā of class and object and is much cleaner to have the 2 separated