LearnFrenzy
Sign in Take a free test

Python Programming · Topic 18 of 25

OOP in Python Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

OOP in Python · Study material

Object-oriented programming (OOP) groups data and the functions that work on it into classes. A class is a blueprint – Student, BankAccount, Product – and each object (instance) made from it has its own data. In Python everything is an object, and classes are how real projects – Django models, game sprites, API clients – are organised. Interviews ask about self and __init__, class vs instance attributes, __str__ vs __repr__, private attributes, properties and @classmethod vs @staticmethod. This topic covers all of it (inheritance and polymorphism come next), then 50 practice questions run on Python 3.

On this page

  • Classes, objects, __init__ and self
  • Instance attributes vs class attributes
  • __str__, __repr__ and __eq__
  • Encapsulation: _private, __mangled and properties
  • @classmethod and @staticmethod
  • @dataclass and container methods like __len__

Classes, objects, __init__ and self

class Student: defines a class. Calling it – Student("Asha", [91, 88]) – creates an object and runs __init__, which stores the object's data as attributes on self. Every method receives the object it is called on as its first parameter, named self by convention: asha.average() is really Student.average(asha).

class Student:
    """A student with a name and marks."""

    def __init__(self, name, marks):      # runs when an object is created
        self.name = name                  # instance attributes: one copy per object
        self.marks = marks

    def average(self):                    # a method: self is the object it is called on
        return sum(self.marks) / len(self.marks)

    def is_topper(self, cutoff=90):
        return self.average() >= cutoff

asha = Student("Asha", [91, 88, 95])      # create (instantiate) objects
ravi = Student("Ravi", [72, 65, 70])

print(asha.name, round(asha.average(), 1), asha.is_topper())
print(ravi.name, round(ravi.average(), 1), ravi.is_topper())
print(type(asha).__name__, isinstance(ravi, Student), asha is ravi)

Output

Asha 91.3 True
Ravi 69.0 False
Student True False

Instance attributes and class attributes

Attributes set on self belong to one object. Attributes defined in the class body belong to the class and are shared by all its objects – good for constants and counters. Reading obj.attr looks in the object first, then in the class. Assigning obj.attr = … always creates or changes an instance attribute, hiding the class attribute for that object only; to change the shared value, assign through the class.

class Employee:
    company = "LearnFrenzy"          # class attribute: shared by all instances
    count = 0

    def __init__(self, name):
        self.name = name             # instance attribute
        Employee.count += 1          # update the shared counter through the CLASS

a = Employee("Asha")
b = Employee("Ravi")
print(a.company, b.company, Employee.count)

a.company = "Startup"                # creates an INSTANCE attribute that hides the class one
print(a.company, b.company, Employee.company)
print(vars(a), vars(b))

Output

LearnFrenzy LearnFrenzy 2
Startup LearnFrenzy LearnFrenzy
{'name': 'Asha', 'company': 'Startup'} {'name': 'Ravi'}

The shared mutable class attribute trap

A mutable class attribute (a list or dict in the class body) is one object shared by every instance. Mutating it through any instance changes it for all. Create per-object containers in __init__.

class Team:
    members = []                     # ✘ ONE list shared by every Team

    def add(self, name):
        self.members.append(name)    # mutates the shared class list

class TeamFixed:
    def __init__(self):
        self.members = []            # ✔ a new list for each object

    def add(self, name):
        self.members.append(name)

t1, t2 = Team(), Team()
t1.add("Asha")
print(t2.members)

f1, f2 = TeamFixed(), TeamFixed()
f1.add("Asha")
print(f2.members, f1.members)

Output

['Asha']
[] ['Asha']

__str__, __repr__ and __eq__

Dunder (double-underscore) methods let your objects work with Python's built-in operations. __str__ gives the friendly text used by print(); __repr__ gives the developer text used in lists, the REPL and debugging (and as a fallback for __str__). Without __eq__, == compares identity, so two objects with the same data are not equal. If you define __eq__, define __hash__ too if objects should go into sets or be dict keys.

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __str__(self):               # friendly text for print() and str()
        return f"({self.x}, {self.y})"

    def __repr__(self):              # unambiguous text for debugging, lists, the REPL
        return f"Point({self.x}, {self.y})"

    def __eq__(self, other):         # == compares values instead of identity
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)

    def __hash__(self):              # keep equal objects usable in sets and as dict keys
        return hash((self.x, self.y))

p, q = Point(2, 3), Point(2, 3)
print(p)
print([p, q], repr(p))
print(p == q, p is q, len({p, q}))

Output

(2, 3)
[Point(2, 3), Point(2, 3)] Point(2, 3)
True False 1

Encapsulation and properties

Python has no private keyword. A single underscore (_balance) marks an attribute as internal by convention. A double underscore (__pin) triggers name mangling to _ClassName__pin, which avoids accidental clashes in subclasses – it is not real security. A @property lets you start with a plain attribute and later add validation or computation without changing the code that uses it.

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance      # _name: "internal, please don't touch" (convention)
        self.__pin = "1234"          # __name: name-mangled to _BankAccount__pin

    @property
    def balance(self):               # read like an attribute: acc.balance
        return self._balance

    @balance.setter
    def balance(self, value):        # assignment runs validation
        if value < 0:
            raise ValueError("balance cannot be negative")
        self._balance = value

acc = BankAccount("Asha", 1000)
acc.balance += 500
print(acc.balance)
try:
    acc.balance = -10
except ValueError as e:
    print("ValueError:", e)
print(hasattr(acc, "__pin"), acc._BankAccount__pin)

Output

1500
ValueError: balance cannot be negative
False 1234

@classmethod and @staticmethod

A class method receives the class (cls) instead of an instance – ideal for alternative constructors such as Date.from_string("05-11-2028"), which also work correctly for subclasses. A static method receives neither; it is an ordinary function placed in the class because it belongs there logically. Both can be called on the class or an instance.

class Date:
    def __init__(self, day, month, year):
        self.day, self.month, self.year = day, month, year

    @classmethod
    def from_string(cls, text):           # alternative constructor: gets the CLASS
        d, m, y = map(int, text.split("-"))
        return cls(d, m, y)

    @staticmethod
    def is_leap(year):                    # a plain function kept in the class namespace
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

    def __str__(self):
        return f"{self.day:02d}/{self.month:02d}/{self.year}"

d = Date.from_string("05-11-2028")
print(d, Date.is_leap(d.year), d.is_leap(2026))

Output

05/11/2028 True False

@dataclass

For classes that mainly hold data, @dataclasses.dataclass writes __init__, __repr__ and __eq__ for you from type-annotated fields. Use field(default_factory=list) for mutable defaults; order=True adds comparisons and frozen=True makes instances immutable.

from dataclasses import dataclass, field

@dataclass
class Product:
    name: str
    price: float
    tags: list = field(default_factory=list)   # safe mutable default

    def with_gst(self):
        return round(self.price * 1.18, 2)

p = Product("Notebook", 45.0)
q = Product("Notebook", 45.0)
print(p)                                       # __repr__ generated
print(p == q, p.with_gst())                    # __eq__ generated
p.tags.append("stationery")
print(p.tags, q.tags)

Output

Product(name='Notebook', price=45.0, tags=[])
True 53.1
['stationery'] []

Common mistakes

  • Forgetting self in a method definition – TypeError: takes 0 positional arguments but 1 was given.
  • Using name instead of self.name inside a method – NameError.
  • Mutable class attributes – shared by all objects.
  • Misspelling __init__ (_init_, __int__) – the constructor never runs.
  • __str__ that prints instead of returning – TypeError: __str__ returned non-string.
  • Expecting == to compare data without __eq__.
  • Assigning to a property with no setter – AttributeError.

Key points to remember

  • A class is a blueprint; objects are instances with their own attributes.
  • __init__ initialises a new object; self is that object.
  • Class attributes are shared; instance attributes are per object.
  • obj.attr = value always sets an instance attribute.
  • __str__ for users, __repr__ for developers; __eq__ for ==.
  • _name is a convention; __name is mangled; @property validates access.
  • @classmethod gets cls; @staticmethod gets nothing.

Frequently asked questions

Is self a keyword?

No – it is just the conventional name for the first parameter. Any name works, but always use self.

Does Python have private members?

Not enforced ones. _name signals "internal", and __name is mangled to avoid clashes, but both can still be reached.

Is __init__ the constructor?

Strictly, __new__ creates the object and __init__ initialises it. In everyday code __init__ is what you write.

Where can I learn more?

Read Python Classes and Objects and Dunder Methods and Dataclasses in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links