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?
- self refers to the particular instance the method is being called on.
- Python passes the instance explicitly as the first argument, so you write self to access that object's attributes and methods.
- It's explicit by design — 'explicit is better than implicit' — unlike Java's implicit 'this'.
Answer: self is the current instance, passed explicitly as the first method parameter; you use it to access the object's own attributes.
Worked example
What's the difference between an instance variable and a class variable?
- An instance variable (self.x, set in __init__) belongs to one object — each instance has its own.
- A class variable is defined in the class body and shared by all instances.
- Shared mutable class variables are a trap: a change via one instance is visible to all; use instance variables for per-object data.
Answer: Instance variables (self.x) are per-object; class variables are shared by all instances — mutable ones are a shared-state trap.
⚠ 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__).