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









