Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 12

Python OOPs

9 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Object-oriented programming models a program as objects that bundle data (attributes) and behaviour (methods).

Python supports classes, constructors, inheritance, abstraction, encapsulation, access conventions, overloading-style techniques and polymorphism.

OOP is the backbone of large Python code bases and a guaranteed topic in exams, vivas and interviews.

Frameworks (Django models, Flask extensions), games, GUI toolkits, data-science libraries and APIs are all designed with classes.

1

Python OOPs Concepts

Object-oriented programming (OOP) is a paradigm that organises software around objects. An object is an instance of a class; the class is a blueprint that defines attributes (data) and methods (functions). Python is multi-paradigm but everything in it, including integers and functions, is an object.

In short: A class is a cookie cutter; objects are the cookies. Each cookie has its own data but shares the same shape and abilities.

Four pillars of OOP

Think about it

Every later OOP topic builds on this vocabulary and exams always begin with the four pillars. A Car class holds colour and speed (data) and offers drive() and brake() (behaviour). Many cars, one blueprint.

The four pillars are: (1) Encapsulation - bundle data with the methods that use it and control access; (2) Abstraction - expose what an object does, hide how; (3) Inheritance - a child class reuses and extends a parent; (4) Polymorphism - one interface, many implementations.

Python adds dynamic features: attributes can be added at run time, classes are themselves objects, and there are no compiler-enforced private members.

OOP improves reuse, modularity and maintainability, but plain functions are still fine for small scripts.

Use type(obj) to see the class and isinstance(obj, Class) to test membership.

Key points

  • Class: Blueprint that defines attributes and methods.
  • Object / instance: A concrete thing created from a class.
  • Attribute: A variable stored on an object or class.
  • Method: A function defined inside a class that works on an instance (self).
  • self: Conventional name for the instance passed as first argument.

Example

Code
class Dog:
    species = "Canis familiaris"        # class attribute (shared)

    def __init__(self, name, age):      # constructor
        self.name = name                # instance attributes
        self.age = age

    def speak(self):                    # method
        return f"{self.name} says Woof"

rex = Dog("Rex", 3)
lia = Dog("Lia", 5)
print(rex.speak())                      # Rex says Woof
print(lia.name, lia.age)                # Lia 5
print(type(rex).__name__)               # Dog
print(isinstance(rex, Dog))             # True
print(rex.species is lia.species)       # True: shared
print(type(5), type(len))               # everything is an object
2

Python Classes and Objects

A class statement creates a new type. Calling the class creates an object (instance). Instance attributes live in the object __dict__, class attributes live on the class and are shared. Methods receive the instance as self; @classmethod receives the class (cls); @staticmethod receives neither.

In short: Instance data belongs to one object; class data belongs to all objects of that class.

Class blueprint → objects

Think about it

Distinguishing instance, class and static members is a classic exam question. A Student class counts how many students were created (class attribute) while each student has its own marks (instance attribute).

Attribute lookup order: instance __dict__, then the class, then parent classes.

Assigning obj.

x = value always creates or changes an INSTANCE attribute, even if a class attribute of the same name exists (it shadows it).

Mutable class attributes such as lists are shared by every instance and are a common bug source.

Instance methods are looked up on the class and bound to the object automatically.

Use __str__ for a human-readable string and __repr__ for an unambiguous developer string.

vars(obj) shows the instance dictionary; dir(obj) lists all names.

del obj removes only the name; the object is freed when no references remain.

Key points

  • Instance attribute: Set via self.x; one copy per object.
  • @classmethod: Receives cls; used for factories and class-level data.
  • @staticmethod: No automatic first argument; a plain function inside the class namespace.
  • __dict__: Dictionary that stores an object attributes.

Example

Code
class Student:
    count = 0                                  # class attribute

    def __init__(self, name, marks):
        self.name = name
        self.marks = marks
        Student.count += 1

    def grade(self):                           # instance method
        return "Pass" if self.marks >= 40 else "Fail"

    @classmethod
    def total(cls):                            # class method
        return cls.count

    @staticmethod
    def is_valid(m):                           # static method
        return 0 <= m <= 100

    def __str__(self):
        return f"{self.name} ({self.marks})"

a = Student("Ana", 72)
b = Student("Raj", 35)
print(a.grade(), b.grade())                    # Pass Fail
print(Student.total())                         # 2
print(Student.is_valid(101))                   # False
print(a)                                       # Ana (72)
a.city = "Pune"                                # add attribute at run time
print(vars(a))                                 # {'name': 'Ana', 'marks': 72, 'city': 'Pune'}

# shadowing a class attribute
a.count = 99
print(a.count, Student.count)                  # 99 2
3

Python Constructors

A constructor initialises a new object. In Python the initialiser is the special method __init__(self, ...), called automatically right after the object is created by __new__. __init__ must return None. Python allows only ONE __init__ per class; flexibility comes from default arguments and alternative constructors written as @classmethod.

In short: __init__ is the setup routine that runs the moment you write ClassName(...).

Constructor runs when object is created

Think about it

Constructors, default arguments and the mutable-default trap appear in almost every OOP interview. Rectangle(3, 4) sets width and height; Rectangle.square(5) builds a square using the same initialiser.

Types: default constructor (no parameters except self, or no __init__ at all), parameterised constructor, and constructors with default values.

Because there is no overloading, create alternate ways to build objects with class methods such as from_string or square.

In inheritance, call super().

__init__(...

) so the parent part is initialised.

__new__ actually allocates the object and is rarely overridden (singletons, immutable types).

__del__ is a destructor-like hook called when the object is garbage collected; its timing is not guaranteed, so use context managers for cleanup.

Avoid mutable defaults like def __init__(self, items=[]), because the same list is shared by all instances; use None and create inside.

Key points

  • __init__: Initialiser called after object creation.
  • __new__: Creates the object; runs before __init__.
  • Alternative constructor: A @classmethod that returns cls(...).
  • __del__: Called when the object is about to be destroyed.

Example

Code
class Rectangle:
    def __init__(self, w=1, h=1):              # default values
        self.w = w
        self.h = h

    @classmethod
    def square(cls, side):                     # alternative constructor
        return cls(side, side)

    @classmethod
    def from_string(cls, text):                # "3x4"
        w, h = text.split("x")
        return cls(int(w), int(h))

    def area(self):
        return self.w * self.h

print(Rectangle().area())                      # 1
print(Rectangle(3, 4).area())                  # 12
print(Rectangle.square(5).area())              # 25
print(Rectangle.from_string("6x7").area())     # 42

# mutable default trap and the fix
class Bag:
    def __init__(self, items=None):
        self.items = [] if items is None else items

x, y = Bag(), Bag()
x.items.append(1)
print(y.items)                                 # [] (not shared)

class Resource:
    def __init__(self):
        print("acquired")
    def __del__(self):
        print("released")

r = Resource()                                 # acquired
del r                                          # released (CPython)
4

Python Inheritance

Inheritance lets a child (derived) class acquire the attributes and methods of a parent (base) class: class Child(Parent). The child can add new members or override inherited ones. super() gives access to the next class in the Method Resolution Order (MRO).

In short: A Puppy is a Dog, and a Dog is an Animal; the Puppy automatically gets everything an Animal and Dog can do.

Inheritance: child gets parent traits

Think about it

Code reuse through inheritance and the output of MRO questions are repeatedly examined. A Vehicle base class defines wheels and start(); Car and Bike inherit it and add their own features.

Types: single (one parent), multilevel (chain A -> B -> C), hierarchical (many children of one parent), multiple (several parents) and hybrid (mix).

Overriding replaces a parent method; call super().

method() to extend instead of replace.

For multiple inheritance Python uses C3 linearisation: the MRO is children before parents, left to right, each class once; inspect it with ClassName.

__mro__ or ClassName.

mro().

The diamond problem is resolved by the MRO, and cooperative super() calls make each class run once.

issubclass(C, P) and isinstance(obj, P) test relationships.

Prefer composition ("has-a") when the relationship is not truly "is-a".

Key points

  • Base / parent class: Class whose members are inherited.
  • Derived / child class: Class that inherits from another.
  • Overriding: Redefining an inherited method in the child.
  • MRO: Order in which Python searches classes for an attribute.
  • super(): Proxy to the next class in the MRO.

Example

Code
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return "..."

class Dog(Animal):                      # single inheritance
    def speak(self):                    # overriding
        return f"{self.name}: Woof"

class Puppy(Dog):                       # multilevel
    def __init__(self, name, age):
        super().__init__(name)          # initialise the parent part
        self.age = age
    def speak(self):
        return super().speak() + " (squeaky)"

p = Puppy("Bud", 1)
print(p.speak())                        # Bud: Woof (squeaky)
print(issubclass(Puppy, Animal))        # True
print(isinstance(p, Dog))               # True
print([c.__name__ for c in Puppy.__mro__])   # ['Puppy', 'Dog', 'Animal', 'object']

# multiple inheritance and the diamond
class A:
    def hi(self): return "A"
class B(A):
    def hi(self): return "B"
class C(A):
    def hi(self): return "C"
class D(B, C):
    pass

print(D().hi())                         # B
print([c.__name__ for c in D.__mro__])  # ['D', 'B', 'C', 'A', 'object']
5

Abstraction in Python

Abstraction means exposing only the essential interface and hiding implementation details. Python implements formal abstraction with the abc module: a class that inherits ABC and has at least one @abstractmethod is abstract and cannot be instantiated; subclasses must implement every abstract method.

In short: You press the accelerator without knowing engine internals. An abstract class defines the pedals; each car supplies its own engine.

Abstraction: show what, hide how

Think about it

Interviewers ask how to enforce an interface and why an abstract class cannot be instantiated. A PaymentGateway ABC requires pay(); UpiGateway and CardGateway each implement it differently.

Abstract classes can mix abstract methods (no implementation required) with concrete methods that reuse them (template method pattern).

Trying to instantiate a class that still has unimplemented abstract methods raises TypeError.

Abstract properties and class methods are supported by stacking @property or @classmethod above @abstractmethod.

Python also supports informal abstraction through duck typing and protocols (typing.

Protocol).

Abstraction differs from encapsulation: abstraction is about the design/interface level (what), encapsulation is about protecting data inside the class (how and who can touch it).

Key points

  • ABC: Helper base class from abc that makes a class abstract-capable.
  • @abstractmethod: Marks a method that subclasses must override.
  • Concrete class: Class with all abstract methods implemented.
  • Template method: Concrete method that calls abstract steps.

Example

Code
from abc import ABC, abstractmethod
import math

class Shape(ABC):
    @abstractmethod
    def area(self):
        """Return the area."""

    def describe(self):                        # concrete method using the abstract one
        return f"{type(self).__name__} area = {self.area():.2f}"

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return math.pi * self.r ** 2

class Square(Shape):
    def __init__(self, s):
        self.s = s
    def area(self):
        return self.s ** 2

class Broken(Shape):                           # forgot to implement area()
    pass

try:
    Shape()
except TypeError as e:
    print("Cannot instantiate:", e)

try:
    Broken()
except TypeError:
    print("Broken is still abstract")

for shape in (Circle(2), Square(3)):
    print(shape.describe())                    # Circle area = 12.57 / Square area = 9.00
6

Encapsulation in Python

Encapsulation bundles data and the methods that operate on it inside one class and restricts direct access to the internal state. In Python this is achieved with naming conventions (_protected, __private) and with properties (@property) that validate reads and writes.

In short: Put your money in a bank account and use deposit() and withdraw() instead of reaching into the vault.

Think about it

Property-based validation is the modern, Pythonic answer to the getter/setter questions asked in interviews. A BankAccount never lets the balance become negative because all changes go through methods.

Python trusts the programmer ("we are all consenting adults"), so protection is by convention and name mangling rather than enforcement.

A property turns a method into attribute-style access: @property defines the getter, @x.

setter the setter and @x.

deleter the deleter.

Setters are the right place for validation, so you can start with a public attribute and later convert it into a property without changing callers.

Benefits

data integrity, flexibility to change internals, and reduced coupling.

Read-only attributes are made by defining only a getter; assigning then raises AttributeError.

Key points

  • @property: Turns a method into a managed attribute.
  • Setter: Method decorated with @name.setter that runs on assignment.
  • Name mangling: __x inside class C is stored as _C__x.
  • Invariant: Condition that must always hold, e.g. balance >= 0.

Example

Code
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.__balance = balance               # private by name mangling

    @property
    def balance(self):                         # read-only property
        return self.__balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self.__balance += amount

    def withdraw(self, amount):
        if amount > self.__balance:
            raise ValueError("insufficient funds")
        self.__balance -= amount

acc = Account("Ana", 100)
acc.deposit(50)
print(acc.balance)                             # 150

try:
    acc.balance = 5                            # no setter defined
except AttributeError:
    print("balance is read-only")

print(hasattr(acc, "__balance"))               # False (mangled)
print(acc._Account__balance)                   # 150 (still reachable by convention break)

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius                 # goes through the setter
    @property
    def celsius(self):
        return self._c
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("below absolute zero")
        self._c = value

t = Temperature(25)
t.celsius = 30
print(t.celsius)                               # 30
7

Access Modifiers in Python

Python has no keywords such as public, protected or private. Instead: name = public (accessible anywhere), _name = protected by convention (for use inside the class and its subclasses), __name = private via name mangling (rewritten to _ClassName__name to avoid accidental access and clashes in subclasses).

In short: No locks, only signs: no sign = open to all, one underscore = "staff only, please", two underscores = "private, hard to reach".

Encapsulation: hide inner details

Think about it

The difference between _x and __x and the mangled name is a favourite interview question. Library authors prefix helper methods with an underscore to signal they may change without notice.

Single leading underscore is a hint to other programmers; the interpreter does not enforce it (except that from module import * skips such names).

Double leading underscore without trailing underscores triggers name mangling, so Child cannot accidentally read Parent.

__x as self.

__x - it looks for _Child__x.

Mangling can be bypassed using obj.

_Parent__x, proving it is not true security.

Names with double underscores on both sides (__init__) are special "dunder" names reserved by Python and are not mangled.

For real protection use properties, closures or operating-system level controls; for internal helpers prefer a single underscore.

Key points

  • Public: name - no restriction.
  • Protected: _name - convention for subclasses.
  • Private: __name - mangled to _Class__name.
  • Dunder: Special names with double underscores both sides.

Example

Code
class Demo:
    def __init__(self):
        self.pub = 1
        self._prot = 2
        self.__priv = 3

    def show(self):
        return self.pub, self._prot, self.__priv

class Child(Demo):
    def peek_protected(self):
        return self._prot                      # fine: subclass use

    def peek_private(self):
        return self.__priv                     # looks for _Child__priv

d = Demo()
print(d.pub, d._prot)                          # 1 2
print(d.show())                                # (1, 2, 3)
print(list(vars(d)))                           # ['pub', '_prot', '_Demo__priv']
print(d._Demo__priv)                           # 3 (mangled name works)

c = Child()
print(c.peek_protected())                      # 2
try:
    c.peek_private()
except AttributeError as e:
    print("AttributeError:", e)                # no attribute '_Child__priv'

try:
    print(d.__priv)
except AttributeError:
    print("direct access to __priv fails")
8

Method Overloading in Python

Method overloading means several methods with the same name but different parameter lists. Python does NOT support it directly: when a name is defined twice in a class the later definition replaces the earlier one. Equivalent behaviour is achieved with default arguments, *args/**kwargs, type checks, or functools.singledispatch / singledispatchmethod.

In short: You cannot have two add() methods with different signatures. Write one flexible add() or dispatch on type.

Think about it

The statement "Python does not support method overloading" and its workarounds is asked in nearly every interview. A print_value function that formats ints, lists and strings differently without a chain of if statements.

Techniques: (1) default parameters - def area(a, b=None); (2) variable arguments - def add(*nums); (3) isinstance checks inside one method; (4) functools.

singledispatch which picks an implementation from the TYPE of the FIRST argument; (5) the third-party multipledispatch package for multiple arguments.

Python 3.8+ provides singledispatchmethod for methods.

Operator overloading is a different, fully supported feature using dunder methods such as __add__ and __eq__.

Method overriding (child replaces parent method) is also separate from overloading.

Key points

  • Overloading: Same name, different signatures (compile-time idea).
  • Overriding: Subclass replaces a parent method.
  • singledispatch: Decorator that chooses a function by the type of argument 1.
  • *args: Collects extra positional arguments into a tuple.

Example

Code
from functools import singledispatch

class Broken:
    def f(self, a):
        return "one arg"
    def f(self, a, b):                         # replaces the first f
        return "two args"

try:
    Broken().f(1)
except TypeError as e:
    print("TypeError:", e)

class Calc:
    def add(self, *nums):                      # variable arguments
        return sum(nums)

    def area(self, a, b=None):                 # default argument
        return a * a if b is None else a * b

c = Calc()
print(c.add(1, 2), c.add(1, 2, 3, 4))          # 3 10
print(c.area(4), c.area(4, 5))                 # 16 20

@singledispatch
def show(x):
    return f"object: {x}"

@show.register(int)
def _(x):
    return f"int: {x}"

@show.register(list)
def _(x):
    return f"list of {len(x)} items"

print(show(5))                                 # int: 5
print(show([1, 2, 3]))                         # list of 3 items
print(show(2.5))                               # object: 2.5
9

Polymorphism in Python

Polymorphism ("many forms") lets the same interface - a function name, operator or method call - work with objects of different types, each responding in its own way. Python provides it through method overriding, duck typing, built-in polymorphic functions (len, +) and operator overloading.

In short: Say speak() to a Dog, Cat or Duck: each answers differently, and the caller does not care which one it is.

Polymorphism: one call, many forms

Think about it

Polymorphism ties the OOP pillars together and is the final concept examiners test with output questions. A drawing program calls shape.draw() for Circle, Rectangle and Triangle without checking the type.

Kinds: (1) Overriding-based (inheritance) polymorphism; (2) Duck typing - "if it walks like a duck and quacks like a duck": no common base class is required, only the needed methods; (3) Operator polymorphism - + adds numbers, concatenates strings and lists; (4) Built-in function polymorphism - len() works on str, list, dict, range.

Define __add__, __len__, __eq__ and so on in your own classes to plug into the same syntax.

Polymorphism reduces if/elif chains by moving behaviour into the object.

Use abstract base classes when you want to enforce the interface instead of trusting duck typing.

Key points

  • Duck typing: Suitability is decided by available methods, not class.
  • Operator overloading: Giving operators meaning for custom classes through dunder methods.
  • Late binding: Method chosen at run time from the actual object.

Example

Code
class Dog:
    def speak(self): return "Woof"
class Cat:
    def speak(self): return "Meow"
class Robot:                                   # unrelated class, same method name
    def speak(self): return "Beep"

def make_noise(thing):
    print(thing.speak())

for obj in (Dog(), Cat(), Robot()):
    make_noise(obj)                            # Woof Meow Beep

print(len("abc"), len([1, 2]), len({1: "a"}))  # 3 2 1
print(1 + 2, "a" + "b", [1] + [2])             # 3 ab [1, 2]

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

print(Vector(1, 2) + Vector(3, 4))             # Vector(4, 6)

# overriding polymorphism
class Shape:
    def area(self): return 0
class Rect(Shape):
    def __init__(self, w, h): self.w, self.h = w, h
    def area(self): return self.w * self.h
class Circle(Shape):
    def __init__(self, r): self.r = r
    def area(self): return round(3.14159 * self.r ** 2, 2)

print([s.area() for s in (Rect(2, 3), Circle(1))])   # [6, 3.14]

Solved examples

Example 01 · Basic

Create a class Circle with radius, a method area() and a __str__ method. Print a circle of radius 3.

Given Data:
    Required To Find:

    Class definition and output

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Define __init__(self, r) and store self.r
    Step 2: area() returns pi * r ** 2
    Step 3: __str__ returns a formatted string
    Final Answer: import math class Circle: def __init__(self, r): self.r = r def area(self): return math.pi * self.r ** 2 def __str__(self): return f"Circle(r={self.r}, area={self.area():.2f})" print(Circle(3)) # Circle(r=3, area=28.27)

    Approach note: Use f-string format specs like :.2f for tidy output.

    Example 02 · Intermediate

    Find the output: class P: def show(self): print("P") class Q(P): def show(self): super().show(); print("Q") Q().show()

    Given Data:
      Required To Find:

      Printed lines

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Q().show() calls Q.show
      Step 2: super().show() runs P.show first, printing P
      Step 3: Then Q prints Q
      Final Answer: P Q

      Approach note: super() inside an overriding method lets you extend, not replace, the parent behaviour.

      Example 03 · Intermediate

      Why does Shape() raise TypeError if Shape inherits ABC and has an @abstractmethod? How do you fix it?

      Given Data:
        Required To Find:

        Explanation and fix

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: A class with unimplemented abstract methods cannot be instantiated
        Step 2: Create a subclass that overrides every abstract method
        Step 3: Instantiate the subclass instead
        Final Answer: Abstract classes are incomplete by design. Subclass Shape, implement area(), then create the subclass object.

        Approach note: The TypeError message names the abstract methods still missing.

        Example 04 · Basic

        Define class Counter with __init__ setting self.n = 0 and method bump that adds 1. Create one object, call bump twice, print n.

        Given Data:
          Required To Find:

          Final n value and sketch

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: __init__ runs on construction and sets n to 0
          Step 2: Each bump adds 1
          Step 3: After two bumps n is 2
          Final Answer: class Counter: def __init__(self): self.n = 0 def bump(self): self.n += 1 c = Counter(); c.bump(); c.bump(); print(c.n) # 2

          Approach note: self always refers to the instance receiving the method call.

          Real-world applications

          Python

          Using Python OOPs Concepts in real projects

          Frameworks (Django models, Flask extensions), games, GUI toolkits, data-science libraries and APIs are all designed with classes.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Python supports method overloading like Java.

          Why this is wrong: A second def with the same name simply replaces the first.

          ✅ Verified Truth: Use default arguments, *args or singledispatch to get similar behaviour.

          ⚠️ Exam Tip: State this exact sentence in answers, then show the workaround.

          ❌ Myth: Double-underscore attributes are truly private.

          Why this is wrong: Name mangling only renames the attribute to _Class__name.

          ✅ Verified Truth: Access is still possible; it is a protection against accidents.

          ⚠️ Exam Tip: Mention _Class__name when asked how to access a private member.

          ❌ Myth: A class attribute is copied into every object.

          Why this is wrong: Class attributes are stored once on the class and shared.

          ✅ Verified Truth: Assigning obj.x creates a new instance attribute that shadows it.

          ⚠️ Exam Tip: Mutable class attributes (lists) cause shared-state bugs.

          Revision notes

          Object-oriented programming models a program as objects that bundle data (attributes) and behaviour (methods). Python supports classes, constructors, inheritance, abstraction, encapsulation, access conventions, overloading-style techniques and polymorphism.

          High-Yield Quick Revision Points

          1. Four pillars: encapsulation, abstraction, inheritance, polymorphism.
          2. __init__ initialises; one per class; use defaults and @classmethod factories.
          3. super() follows the MRO; check with Class.__mro__.
          4. ABC + @abstractmethod: cannot instantiate until all are implemented.
          5. _x protected by convention; __x mangled to _Class__x.
          6. No true method overloading: use defaults, *args, singledispatch.
          7. Duck typing: if the method exists, it works.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which method is automatically called when an object is created?

          Question 2 · MCQ (Interview / semester)

          What does the first parameter of an instance method usually named self represent?

          Question 3 · MCQ (Interview / semester)

          In class D(B, C), the MRO searches classes in which order?

          Question 4 · MCQ (Interview / semester)

          Which module is used to create abstract base classes?

          Question 5 · MCQ (Interview / semester)

          Inside class C, the attribute __x is stored as

          Question 6 · MCQ (Interview / semester)

          If a class defines two methods named f with different parameters, what happens?

          Question 7 · MCQ (Interview / semester)

          Duck typing means