PART 3 β€’ LEVEL 11

πŸ—οΈ Object-Oriented Python

Model real entities as cooperating objects that combine data with behavior and grow safely through inheritance, composition and polymorphism.

⏱ 110–125 minutesπŸ“š 8 conceptsπŸ’» 5 programs🧠 6-question quiz
student.pyPython 3
class Student:
    def __init__(self, name, marks):
        self.name = name
        self.marks = marks

    def result(self):
        return "Pass" if self.marks >= 40 else "Fail"
KEY IDEAState + Behaviour = Object

By the End of This Level

You will be able to design small object-oriented Python solutions.

01

Create classes, objects, constructors and instance attributes.

02

Protect state through clear methods and controlled access.

03

Reuse and specialise behaviour through inheritance.

04

Apply overriding, polymorphism and composition appropriately.

01

Classes and Objects

A class describes a category of objects; an object is one concrete instance created from that class.

A class groups related data and functions under one name. Attributes represent state, while methods represent actions that use or change that state.

Object

A runtime value with its own identity, type and state. Multiple objects from the same class can store different attribute values.

1Define ClassDescribe the model
β†’
2Call ClassRequest an object
β†’
3InitialiseStore object state
β†’
4Use ObjectAccess its behaviour
EXAMPLE 1

Create Two Student Objects

class Student:
    pass

first = Student()
second = Student()
print(type(first) == type(second))
Output
True
02

__init__, self and Attributes

Python calls __init__ after creating an instance so its starting state can be established.

PartPurposeExample
__init__Initialises a new instancedef __init__(self, name):
selfRefers to the current instanceself.name
Instance attributeStores per-object stateself.marks = marks
Object creationCalls the classStudent("Asha", 88)
self is explicit

Python supplies the current object automatically during a method call, but the method definition must declare self as its first parameter.

03

Instance Methods

An instance method receives self and performs work using the current object’s attributes.

EXAMPLE 2

Calculate a Rectangle’s Area

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

box = Rectangle(8, 5)
print("Area =", box.area())
Output
Area = 40
Call syntax

box.area() is conceptually similar to Rectangle.area(box); the instance becomes the self argument.

04

Encapsulation and Properties

Encapsulation keeps state and the rules that protect it together inside a class.

CONVENTION

Non-public attribute

A leading underscore communicates that an attribute is an internal implementation detail.

self._balance = 0
PROPERTY

Controlled access

@property exposes method logic through attribute-like syntax and can validate assignments.

@property
def balance(self):
    return self._balance
Name mangling

A double-leading name such as self.__pin is transformed to reduce accidental access; it does not provide security or true privacy.

05

Class Attributes, Class Methods and Static Methods

Class members belong to the class itself and support information or behaviour shared across instances.

MemberFirst parameterTypical use
Instance methodselfRead or change one object
Class methodclsAlternative constructor or class-level operation
Static methodNone supplied automaticallyRelated utility that needs no instance or class state
Class attributeNot applicableShared constant or counter
EXAMPLE 3

Track a Shared School Name

class Student:
    school = "CodeBhavya Academy"

    def __init__(self, name):
        self.name = name

student = Student("Bhavya")
print(student.school)
Output
CodeBhavya Academy
06

Inheritance and super()

Inheritance creates a specialised class from an existing class when a genuine β€œis-a” relationship exists.

1Base ClassCommon state
β†’
2SubclassDeclare relationship
β†’
3super()Reuse base setup
β†’
4SpecialiseAdd new behaviour
EXAMPLE 4

Specialise an Employee

class Employee:
    def __init__(self, name):
        self.name = name

class Developer(Employee):
    def __init__(self, name, language):
        super().__init__(name)
        self.language = language
Relationship
Developer is an Employee
07

Method Overriding and Polymorphism

A subclass overrides a method by defining a method with the same name but specialised behaviour.

OVERRIDE

Specialise inherited behaviour

A subclass supplies its own implementation while keeping the method name expected by callers.

class Dog:
    def speak(self):
        return "Woof"
POLYMORPHISM

Program to behaviour

Different objects respond to the same operation, allowing callers to work with a common interface.

for animal in animals:
    print(animal.speak())
Duck typing

Python often cares about the behaviour an object provides rather than requiring it to inherit from one particular base class.

08

Composition

Composition places one object inside another when the relationship is naturally β€œhas-a”.

INHERITANCE

Is-a relationship

A Developer is an Employee. Use inheritance when the subtype can safely replace the base type.

COMPOSITION

Has-a relationship

A Car has an Engine. Delegate work to the contained object instead of forcing an unrelated class hierarchy.

🧩

Flexible

Components can be replaced independently.

πŸ§ͺ

Testable

Each collaborator can be tested alone.

πŸ”§

Maintainable

Responsibilities stay clearly separated.

♻️

Reusable

One component can serve many owners.

Object-Oriented Errors to Avoid

01
Forgetting self

Instance methods must declare self first and use it to access instance state.

02
Sharing mutable class state accidentally

Put per-object lists and dictionaries inside __init__, not directly on the class.

03
Using inheritance only to reuse code

Inheritance should represent a valid substitutable β€œis-a” relationship.

04
Exposing uncontrolled state changes

Use methods or properties when an attribute must obey validation rules.

QUICK REVISION

πŸ“Œ Object-Oriented Python β€” Quick Revision

Review these ten rules before attempting the quiz and programming problems.

01

A class describes the state and behaviour of objects.

02

An object is one instance of a class.

03

__init__ establishes an instance’s initial state.

04

self refers to the current instance.

05

Instance attributes store per-object values.

06

Class attributes are shared through the class.

07

Encapsulation keeps state and its rules together.

08

Inheritance models a substitutable β€œis-a” relationship.

09

Overriding gives a subclass specialised behaviour.

10

Composition models a flexible β€œhas-a” relationship.

🧠 Level 11 Quiz

Select one answer for each question, then check your score.

1. What does self refer to inside an instance method?

2. Which method normally establishes an object’s initial attributes?

3. Which member is normally shared by all instances?

4. What does super() help a subclass do?

5. Which concept allows different objects to respond to the same method name?

6. A car containing an engine is primarily which relationship?

PROGRAMMING PROBLEMS

πŸ’» CodeBhavya Object-Oriented Challenges

Design each class and run it in the browser. The checker uses the displayed input and exact expected output.

0 / 5Solved independently
0Completed with solution
0 / 500Best score
0%Progress
1. Student Result Class

Create a Student class that stores a name and marks and returns Pass for marks of at least 40.

Sample inputs: Bhavya, 78Expected output: Bhavya: Pass
2. Rectangle Measurements

Create a rectangle object with separate methods that return its area and perimeter.

Sample inputs: 8, 5Expected output: Area = 40 and Perimeter = 26
3. Bank Account Operations

Store a starting balance, deposit an amount and withdraw an amount only when sufficient funds are available.

Sample inputs: 1000, 500, 300Expected output: Balance = 1200
4. Developer Inheritance

Create Employee and Developer classes. Reuse the base constructor and return a developer summary.

Sample inputs: Asha, 60000, PythonExpected output: Asha | 60000 | Python
5. Shape Polymorphism

Override area() in rectangle and square subclasses, then call the same method on both objects.

Sample inputs: 6, 4, 5Expected output: Rectangle = 24 and Square = 25
KEY TAKEAWAY

🎯 Give Every Object a Clear Responsibility

1Model State

Store meaningful attributes.

β†’
2Define Behaviour

Keep rules in methods.

β†’
3Reuse Carefully

Inherit only for β€œis-a”.

β†’
4Compose Systems

Connect focused objects.

Object orientation is most useful when it clarifies responsibilities. Well-designed objects protect their own valid state, expose purposeful behaviour and collaborate through small, predictable interfaces.

INTERACTIVE LEARNING

🎬 Object Creation β€” Visual Flow

Follow a class call as Python creates, initialises and returns a usable object.

PROGRAM TRACING

πŸ”Ž Program Tracing β€” Constructor and Method Call

Trace a rectangle object from class call through attribute storage and area calculation.

INTERVIEW PREPARATION

🎀 Object-Oriented Python β€” Interview Questions

Answer aloud before opening each explanation.

1.

What is the difference between a class and an object?

2.

Why is self required in instance method definitions?

3.

How do instance attributes and class attributes differ?

4.

What is method overriding?

5.

When should composition be preferred over inheritance?

6.

What does polymorphism improve in a program?

EXTRA TIPS

πŸ’‘ Object-Oriented Python β€” Extra Tips

  • 01

    Name classes with nouns in PascalCase, such as BankAccount.

  • 02

    Keep methods small and focused on the responsibility of their class.

  • 03

    Create per-object mutable attributes inside __init__.

  • 04

    Expose behaviour instead of asking callers to manipulate internal state directly.

  • 05

    Use super() so cooperative inheritance follows Python’s method resolution order.

  • 06

    Prefer composition when collaborators may change independently.

EXTRA PRACTICE

✍️ Object-Oriented Python β€” Extra Practice Questions

  1. Create a Book class with title, author and a display method.
  2. Build a Circle class that returns area and circumference.
  3. Add controlled deposit and withdrawal methods to an account.
  4. Use a class attribute to count how many objects were created.
  5. Create a class method that builds a student from a comma-separated string.
  6. Validate an age assignment using a property setter.
  7. Derive Car and Bike from a Vehicle class.
  8. Override a fare() method for bus and taxi objects.
  9. Model a computer that contains processor and memory objects.
  10. Explain why an unrelated helper class should not inherit only for code reuse.

Object-Oriented Python Complete

When you can design classes, protect instance state and explain inheritance, overriding, polymorphism and composition, mark this level complete and continue.