liveBook · Manning

Superclass

As explained in The Quick Python Book, Fourth Edition

A base class is a class from which another class inherits attributes and behavior.

A superclass, also called a base or parent class, holds behavior that subclasses inherit. In Python, `class Circle(Shape):` makes `Shape` the superclass of `Circle`. If `Circle` has no `move()` method, a call to `circle.move(...)` uses the method defined on `Shape`. section 15.8

class Circle(Shape):                                #1
    pi = 3.14159                                    #2
    all_circles = []                                #2
    def __init__(self, r=1, x=0, y=0):              #3
        super().__init__(x, y)                      #4
        self.radius = r
        self.__class__.all_circles.append(self)     #5
    @classmethod                                    #6
    def total_area(cls):
        area = 0
        for circle in cls.all_circles:
            area += cls.circle_area(circle.radius)  #7
        return area
    @staticmethod
    def circle_area(radius):                        #8
        return Circle.pi * radius * radius          #9

`Circle` inherits from `Shape` but defines its own initializer. `super().__init__(x, y)` initializes the inherited position before `Circle` sets its radius. section 15.8

Put shared work in the superclass when subclasses differ only in small details. An HTML-element example keeps string rendering in `Element`; `Html`, `Body`, and `P` supply their tag names. Adding another supported element then needs little new code. section 15.14.2

class Element:
   tag = ""

   def __init__(self, text="", subelement=None):
       self.text = text
       self.subelement = subelement

   def __str__(self):
       result = f"<{self.tag}>\n"
       if self.text:
           result += self.text + "\n"
       if self.subelement:
           result += str(self.subelement)
       result += f"</{self.tag}>\n"
       return result

class Html(Element):
   tag = "html"

class Body(Element):
   tag = "body"

class P(Element):
   tag = "p"

# Usage:
para = P(text="this is some body text")
doc_body = Body(text="This is the body", subelement=para)
doc = Html(subelement=doc_body)
print(doc)

The shared `__str__` method renders an element and recursively renders its subelement. Each subclass supplies a lowercase `tag` class attribute. section 15.14.2

Inherited variables need care. Methods inherited from a superclass and methods defined on a subclass can access the same instance variable through `self`. A subclass also inherits access to a superclass’s class variable, but assigning that name on the subclass creates a separate class variable; assigning it on an instance creates an instance variable. section 15.7

To inspect a relationship, a class’s `__bases__` gives its direct base classes. `issubclass(Circle, Shape)` checks a class relationship, while `isinstance(circle, Shape)` checks whether an object belongs to a class or one of its subclasses. section 17.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through method lookup, initializer calls, variable shadowing, and relationship checks without exploring inheritance implementation internals.
Examples
Uses shapes with inherited movement and HTML elements with shared string rendering; contrasts superclass, subclass, and instance variable assignments.
What it assumes
Assumes general object-oriented programming familiarity in the quick overview while demonstrating Python class and initializer syntax.
What you can do after
Build it from scratch: place shared behavior in a Python superclass, initialize it from a subclass, and check inheritance relationships.
How it connects
Connects superclasses to inheritance, subclasses, instance variables, class variables, method lookup, and type checking.

Also explained in

Compare how 10 books explain superclass →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.