Implementing Class Attributes in Python Classes

Pavol Kutaj
2 min readJul 16, 2022

--

The aim of this pagešŸ“ is to show how class attributes are defined and used in Python.

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 the ClassName prefix for class attributes, it confers the same understandability advantage, reducing the amount of detective work required to which objects are being referred to
>>> 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

5. LINKS

--

--

No responses yet