Implementing Class Attributes in Python Classes

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

UnboundLocalError: local variable 'next_serial' referenced before assignment
local variable 'next_serial' referenced before assignme

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
>>> 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com