Python Classes/Objects
Python · Functions & OOP
Theory
A class is a blueprint that describes what data an object holds and what it can do; an object (or instance) is one concrete thing built from that blueprint. Calling the class like a function, Employee('Asha'), creates a new object and automatically runs the special __init__ method, which sets up its attributes.
Inside methods, self refers to the specific object being worked on, so self.name = name stores the name on that object only. Two objects from the same class, Employee('Asha') and Employee('Ravi'), share the class's methods but keep separate attribute values. Attributes set on self are instance attributes; variables written directly in the class body (company = 'TechTown') are class attributes shared by all instances.
Why we use it
Classes let you create many similar objects without repeating setup code. Each object keeps its own state, so you can manage hundreds of employees, orders or accounts with one well-tested definition.
When to use it
Define a class when several values always travel together and need their own operations. If you only need to group a few values with no behaviour, a dict, a namedtuple or a dataclass may be lighter.
How it works
- Python reads class Employee: ...
- Calling Employee('Asha') creates an empty object
- __init__(self, 'Asha') runs on that new object
- self.name = 'Asha' stores an instance attribute
- The finished object is returned and assigned to emp
- emp.name gives 'Asha'
Syntax
obj = ClassName(args)Example
emp = Employee('Asha')
print(emp.name)Key points
- self refers to the current instance
- __init__ is the constructor-like method that sets up attributes
- Calling the class, Employee(...), creates the object
- Instance attributes live on self; class attributes are shared
- Forgetting self in a method definition causes a TypeError when called