Skip to content
UPEEC

Inheritance in Python

A subclass reuses and extends a parent class's behaviour.

Easy
Comments 0
class Sensor:
    def read(self):
        raise NotImplementedError

class TemperatureSensor(Sensor):
    def read(self):
        return 25.0

class LightSensor(Sensor):
    def read(self):
        return 600

super() calls the parent's version of a method. Prefer composition ("has a") over deep inheritance chains ("is a") when objects merely use each other.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.