Concepts / Methods in Classes

Methods in Classes

A child class extends a parent class using the syntax class ChildClass(ParentClass):, inheriting all parent variables and methods automatically.

  • Programming
Interactive lab

Try it: Inheritance and Method Lookup

How a subclass inherits from its parent, how Python finds an attribute by walking the instance, then the class's method resolution order up to object, how overriding and super() work, why the same call does different things on different objects (polymorphism), and what isinstance / issubclass check.

How it works

  1. class Dog(Animal) gives Dog the MRO Dog → Animal → object; Puppy(Dog) gives Puppy → Dog → Animal → object.
  2. obj.name searches obj.__dict__, then each class of type(obj).__mro__ in order; the first class that defines the name wins, so a subclass method overrides the parent's.
  3. super().method() starts the search in the class after the one the current method was defined in, e.g. to run the parent's __init__.
  4. Calling the same method on a list of different objects runs each object's own version (polymorphism).
  5. isinstance(obj, C) is True when C is in type(obj).__mro__; if no class has the name, Python raises AttributeError.

Default run (63 steps): Ready: Animal, Dog, Cat and Puppy, then the statements you picked. Each attribute is searched along the class's MRO. … Finished. Printed: Rex the dog says Woof / Tom the cat says Meow / Bo the dog says Woof! / True / Puppy / Dog / Animal / object.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. Single inheritance only (the lab's MRO code is Python's C3 algorithm, but no class here has two parents).

Educational simulation

Loading the simulation…

One Object, Two Class Levels

Inheritance lets you create a child class that extends a parent class. The child receives the parent class's variables and methods, then can add variables and methods of its own. This means one child-class instance can combine inherited functionality with child-specific functionality.

PartyAnimalname, party()CricketFanpoints, six()inherits
What does a child class receive when it extends a parent class?
Key point

The relationship is one-way: the child inherits from the parent, but the parent does not inherit from the child.

The Inheritance Declaration

To define a child class, place the parent class name in parentheses after the child class name. The pattern is class ChildClass(ParentClass):. In the source example, CricketFan is the child class and PartyAnimal is the parent class, so CricketFan extends PartyAnimal.

python
classstarts a class definitionChildClassnew class(opens parent listParentClassparent class):completes declaration
How does class ChildClass(ParentClass): express the parent-child relationship?
Definition

Inheritance is a one-way class relationship in which the child class receives functionality from the parent class.

Initialization Through super()

A child class may need to initialize both the parent class's variables and its own variables. The child class's __init__ method can call super().__init__() to run the parent class's __init__ method. Call super().__init__() before setting child-specific variables so the parent is initialized first.

python
CricketFan instanceobject creationCricketFan.__init__child setup beginsPartyAnimal.__init__super().__init__()pointschild attribute setupcallssuper().__init__()returns, then continue
How does control move from the child initializer to the parent initializer during object creation?

Inherited and Added Functionality

Worked example

A CricketFan Extends PartyAnimal

Track which variables and methods are available on an instance of CricketFan.

  1. 1
    Parent functionality

    PartyAnimal supplies the name variable and the party() method.

  2. 2
    Child functionality

    CricketFan adds the points variable and the six() method.

  3. 3
    Combined instance

    An instance of CricketFan has access to the inherited name and party(), as well as the child-specific points and six().

Result

The child-class instance combines the parent class's variables and methods with the variables and methods defined by the child class.

python
nameinherited variablepointsnew variableparty()inherited methodsix()new methodcombined on instancecombined on instance
Which methods and attributes come from the parent, and which are added by the child?

Inheritance does not replace the child class's ability to define its own behavior. The child extends the parent by adding new variables and methods while retaining access to the inherited ones.

Finding an Inherited Method

A child-class object can use a method that the child class did not define itself because the method was inherited from the parent. For example, a CricketFan instance can use party(), which comes from PartyAnimal, while also using six(), which is defined in CricketFan.

CricketFan instanceparty() requestedCricketFanmethod defined here?PartyAnimal.party()inherited methodlooks in child classnot defined in child
When a child-class object calls a method it does not define itself, where does the method lookup go next?
jCricketFan instancenamefrom PartyAnimalpointsfrom CricketFanparty()from PartyAnimalsix()from CricketFanhas access tohas access tohas access tohas access to
What attributes exist on a child-class object after parent and child initialization?

Initialization Checklist

  1. 1
    Declare the child class with the parent class in parentheses.
  2. 2
    Define the child class's __init__ method when the child needs its own initialization.
  3. 3
    Call super().__init__() from the child initializer.
  4. 4
    Set up the child-specific variables after the parent initializer returns.
  5. 5
    Add child-specific methods while retaining access to inherited methods.
  • Common mistake

    Defining the child class without naming its parent in parentheses.

    What it looks like
    class CricketFan:
    Why it fails

    This does not express that CricketFan extends PartyAnimal.

    Do this instead

    Use the inheritance form class CricketFan(PartyAnimal):.

  • Common mistake

    Setting child-specific variables without calling the parent initializer.

    What it looks like

    The child sets points but does not call super().__init__().

    Why it fails

    The parent class's required initialization may not be completed.

    Do this instead
    Call super().__init__() before setting child-specific variables.
  • Common mistake

    Assuming the child has only its newly defined methods and variables.

    What it looks like
    Treating a CricketFan instance as if it cannot use party().
    Why it fails

    A child instance also has access to inherited parent functionality.

    Do this instead

    Include both inherited members, such as name and party(), and child members, such as points and six().

  • Common mistake

    Assuming inheritance works in both directions.

    What it looks like

    Expecting PartyAnimal to receive CricketFan's points variable.

    Why it fails

    The hierarchy is one-way from parent to child.

    Do this instead

    Remember that CricketFan inherits from PartyAnimal; PartyAnimal does not inherit from CricketFan.

Practice the Extension Pattern

MEDIUM

Suppose PartyAnimal provides name and party(). Design a child class named CricketFan that calls the parent initializer, adds points, and defines six(). Then list which variables and methods a CricketFan instance can access.

Hints
  • Put PartyAnimal in parentheses after CricketFan.
  • Call super().__init__() inside the child initializer before setting points.
  • Separate inherited members from members introduced by CricketFan.
Worked example

Checking the Completed Design

Explain the members available on an instance named j created from CricketFan.

  1. 1
    Inherited variable

    j has name from PartyAnimal.

  2. 2
    Inherited method

    j can use party() from PartyAnimal.

  3. 3
    Child variable

    j has points from CricketFan.

  4. 4
    Child method

    j can use six() from CricketFan.

Result

j combines the parent functionality and the child functionality.

What to Remember

  1. 1
    Use class ChildClass(ParentClass): to define a child class that extends a parent class.
  2. 2
    A child class inherits the parent class's variables and methods.
  3. 3
    Use super().__init__() inside the child initializer to run the parent initializer.
  4. 4
    Call the parent initializer before setting child-specific variables.
  5. 5
    A child-class instance combines inherited functionality with new functionality defined by the child.

At a glance

  • Inheritance creates a one-way parent-child relationship between classes.
  • The syntax class ChildClass(ParentClass): gives the child access to the parent's variables and methods.
  • super().__init__() runs the parent initializer from the child initializer.
  • A child class can add its own variables and methods while retaining inherited functionality.

Related concepts

More concepts starting with M