Concepts / Methods and the __init__ Constructor

Methods and the __init__ Constructor

A base class defines shared attributes and methods; derived classes inherit from it and add their own specialized features.

  • Programming
Interactive lab

Try it: Classes, Instances and Attributes

How a class creates instances with __init__ and self, why an attribute read checks the instance's __dict__ before the class, why assigning through an instance never changes the class, how a class-level list is shared by every instance, and why obj.method(x) is Class.method(obj, x).

How it works

  1. Dog(...) makes a new, empty instance and calls Dog.__init__(new_object, ...); self.name = ... stores into that object's __dict__.
  2. Reading obj.attr looks in obj.__dict__ first, then in the class.
  3. Assigning obj.attr = value always writes obj.__dict__, so it shadows a class attribute for that one object only.
  4. Mutating a class-level list (self.tricks.append) changes the one list every instance shares.
  5. obj.method is found on the class and bound to obj, so obj.method(x) runs Class.method(obj, x).

Default run (30 steps): Ready: class Dog and the statements you picked. Watch where each attribute is found and where each assignment writes. … Finished. Printed: ['sit'] / Wolf / Canis familiaris / Fido is 5.

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. Object numbers are illustrative, not real id() values.

Educational simulation

Loading the simulation…

One Shared Foundation

Suppose a program models people at a school. Teachers and students are different kinds of school members, but both have a name and an age. Instead of defining those common attributes separately in both classes, a base class named SchoolMember can define them once. Teacher and Student can then inherit those shared features and add their own specialized attributes, such as salary or marks.

SchoolMembername, age, tell()TeachersalaryStudentmarksinherits frominherits from
What does a subclass inherit from its base class, and what can it add on its own?

The base class is the shared foundation. A derived class, also called a subclass, reuses the base class's functionality and can add specialized features. In this example, SchoolMember is the base class, while Teacher and Student are derived classes. A Teacher is therefore a SchoolMember with an additional salary attribute, and a Student is a SchoolMember with an additional marks attribute.

Construction State

What do you think happens?

When a Teacher object is created, which initialization happens first: the SchoolMember initialization or the Teacher-specific initialization?

  • SchoolMember initialization

  • Teacher-specific initialization

  • They cannot both run

Reveal answer
Answer:

SchoolMember initialization

Teacher.__init__ explicitly calls SchoolMember.__init__ first. The inherited name and age attributes are initialized before Teacher adds its salary attribute.

Teacher objectcreation beginsTeacher.__init__runs firstSchoolMember.__init__sets name and agesalaryTeacher-specific attributeinitialized Teachercallsexplicitly callsreturns to subclasscompletes
What happens to inherited attributes when a subclass calls the parent __init__ method during object creation?

When a Teacher object is created, Python runs Teacher.__init__. That method explicitly calls SchoolMember.__init__(self, name, age). The parent initialization establishes the inherited name and age attributes. After that call finishes, Teacher initializes its own salary attribute. Calling the parent constructor is important because it ensures that the inherited part of the object is initialized before the subclass adds its specialized state.

Methods That Specialize

A method defined in a base class is available to derived classes. A derived class can also redefine that method. Redefining an inherited method is called overriding: the subclass supplies its own implementation instead of using only the parent's implementation.

SchoolMember.tell()name and ageTeacher.tell()name, age, salaryStudent.tell()name, age, marksoverride and extendoverride and extend
When a subclass defines a method with the same name as the base class, which implementation runs and how can the subclass extend the original behavior?

SchoolMember defines tell() to display common details. Teacher and Student each define their own tell() method. Inside the Teacher version, the subclass first calls SchoolMember.tell(self), which displays the shared name and age information, and then adds the salary. Student follows the same pattern: it calls the parent tell() method and then adds marks.

Definition

Method overriding means that a derived class redefines a method inherited from its base class. The parent implementation can still be called from the overridden method with the form ParentClassName.method_name(self).

One Base, Many Behaviors

SchoolMembername, ageTeachersalary, tell()Studentmarks, tell()shared tellbehaviorcommon detailsprovides inherited featuresprovides inherited featuresdefines
How can several subclasses use the same attributes and methods from one base class while providing different specialized behavior?

Teacher and Student both reuse SchoolMember's common attributes and can use its methods. Each subclass then supplies behavior appropriate to its own kind of object. This arrangement reduces code duplication: name, age, and the shared part of tell() are defined in one place rather than repeated in every class.

The same design also supports polymorphism. A loop can contain both Teacher and Student objects and call member.tell() for each one without checking the specific class. Python calls Teacher.tell() for a Teacher object and Student.tell() for a Student object. The method call is the same, but the behavior depends on the object receiving it.

member.tell()same callTeacher.tell()name, age, salaryStudent.tell()name, age, marksTeacher objectStudent object
What happens when the same tell() call is made for objects from different derived classes?
Definition

Polymorphism is the ability for the same method call to produce different behavior for different derived classes. It allows code to work with multiple derived classes without knowing each object's specific type.

Mistakes to Avoid

  • Common mistake

    Defining subclass-specific attributes without calling the parent __init__ method.

    What it looks like

    A Teacher initialization adds salary but never calls SchoolMember.__init__(self, name, age).

    Why it fails

    The inherited name and age attributes are not initialized by the base class.

    Do this instead

    Call SchoolMember.__init__(self, name, age) before adding the Teacher-specific salary attribute.

  • Common mistake

    Replacing the parent's method without preserving shared behavior.

    What it looks like

    Teacher.tell() displays salary but does not call SchoolMember.tell(self).

    Why it fails

    The subclass version omits the shared name and age details supplied by the base class.

    Do this instead

    Call the parent tell() method from the overridden method, then add the specialized output.

  • Common mistake

    Checking every object's class before calling tell().

    What it looks like

    A loop separately checks whether each member is a Teacher or a Student.

    Why it fails

    The loop does not use the flexibility provided by polymorphism.

    Do this instead

    Call member.tell(); Python selects the appropriate overridden method for the object.

Practice the Trace

MEDIUM

Use the SchoolMember, Teacher, and Student design to trace the creation of one Teacher and one Student. For each object, identify which attributes come from SchoolMember, which attribute is added by the derived class, which tell() implementation runs, and what shared behavior is preserved by calling the parent method.

Hints
  • Teacher and Student both inherit name and age from SchoolMember.
  • Teacher adds salary, while Student adds marks.
  • The parent tell() method supplies the shared details before the subclass adds its specialized details.
Worked example

Tracing a Teacher Object

What happens when Teacher('Mrs. Shrividya', 40, 30000) is created and its tell() method is used?

  1. 1
    Start subclass initialization

    Python begins by running Teacher.__init__.

  2. 2
    Initialize inherited attributes

    Teacher.__init__ explicitly calls SchoolMember.__init__(self, name, age), which initializes the name and age attributes.

  3. 3
    Initialize the specialized attribute

    After the parent initialization completes, Teacher initializes salary.

  4. 4
    Run the overridden method

    Teacher.tell() calls SchoolMember.tell(self) to display the shared name and age information, then adds the salary.

Result

The Teacher object contains inherited name and age attributes plus its own salary attribute. Its tell() method preserves the base behavior and adds Teacher-specific behavior.

Key Takeaways

  1. 1
    A base class defines attributes and methods shared by related objects.
  2. 2
    A derived class inherits those features and can add specialized attributes and methods.
  3. 3
    A derived class should call the parent __init__ method to initialize inherited attributes.
  4. 4
    Overriding lets a subclass customize a method; calling the parent method lets it extend shared behavior.
  5. 5
    Polymorphism allows one method call, such as member.tell(), to produce the correct behavior for different derived classes.

At a glance

  • SchoolMember centralizes the common name, age, and shared method behavior for teachers and students.
  • Teacher and Student inherit from SchoolMember and add salary or marks.
  • Calling the parent __init__ method initializes the inherited part of a subclass object before subclass-specific attributes are added.
  • Overridden methods can call the parent implementation and then add specialized behavior.
  • Polymorphism lets the same tell() call work with both Teacher and Student objects.

Related concepts

More concepts starting with M