c2cedge
C, Java & Python · D — Python Essentials

Python: OOP & Idioms

Python OOP is lighter than Java's but has its own rules — explicit self, __init__, dunder methods — plus a set of idioms interviewers like to see.

Test weight: High (Py)Skill: Pythonic classesDifficulty: Medium

Python supports classes and objects with a lighter syntax than Java. The constructor is __init__, the current instance is passed explicitly as self, and special 'dunder' methods (__str__, __len__, ...) let your objects integrate with the language. A handful of idioms make code 'Pythonic'.

self, __init__ and instance vs class variables

__init__ initialises a new instance; its first parameter, self, is the instance and must be written explicitly. Instance variables (self.x) are per-object; class variables (defined in the class body) are shared by all instances — mutating a shared mutable class variable affects every instance.

A class with init and inheritance
class Animal:
    def __init__(self, name):
        self.name = name          # instance variable
    def sound(self):
        return "..."

class Dog(Animal):
    def sound(self):              # override
        return "Woof"

d = Dog("Rex")
print(d.name, d.sound())          # Rex Woof
⚡ The edge
  • self is explicit in Python. Every instance method takes self as its first parameter, and you access attributes through it (self.name). Forgetting self is the most common beginner error.
  • Class variables are shared across all instances. A mutable class attribute (e.g. a list defined in the class body) is shared, so appending through one instance is seen by all — use instance variables in __init__ for per-object state.
Worked example
What is 'self' in Python, and why is it explicit?
  1. self refers to the particular instance the method is being called on.
  2. Python passes the instance explicitly as the first argument, so you write self to access that object's attributes and methods.
  3. It's explicit by design — 'explicit is better than implicit' — unlike Java's implicit 'this'.
Worked example
What's the difference between an instance variable and a class variable?
  1. An instance variable (self.x, set in __init__) belongs to one object — each instance has its own.
  2. A class variable is defined in the class body and shared by all instances.
  3. Shared mutable class variables are a trap: a change via one instance is visible to all; use instance variables for per-object data.
⚠ Watch out
  • Forgetting self in a method signature or attribute access is the classic beginner bug.
  • Mutable class variables are shared across instances — define per-object state in __init__.
  • Dunder confusion: __init__ initialises an existing new object; it's not the same as object creation (__new__).
Practice this — take a timed mock →
1,300+ questions, scored, with a weak-area report.
Know who's ready. Not who finished.
HomeLibraryPrivacyTerms