Using class methods and attributes
Generally, we expect objects to be stateful and classes to be stateless. While typical, a stateless class is not a requirement. We can create class objects which have attributes as well as methods. A class can also have mutable attributes, in the rare cases that this is necessary.
One use for class variables is to create parameters that apply to all instances of the class. When a name is not resolved by the object instance, the class is searched next. Here is a small hierarchy of classes that rely on a class-level attribute:
class Units(float): units= None def __repr__(self): text = super().__repr__() return "{0} {1}".format(text, self.units) class Height(Units): units= "inches"
The Units
class definition extends ...
Get Python Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.