O'Reilly logo

Python Essentials by Steven F. Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required