1. Classes and Instances
Object-Oriented Programming (OOP) is a paradigm that groups related data (attributes) and behaviors (methods) into reusable blueprints called classes. An individual object built from a class is an instance. A class is a blueprint for creating objects. In this example, we create a simpleStudent class with two attributes (name and age) and two methods (introduce() and study()).
Output
Key Concepts
- Class:
Student - Object:
student1 - Attributes:
name,age - Methods:
introduce(),study() - Constructor:
__init__()initializes the object’s attributes.
- Defining a class using
class - Initializing attributes using
__init__() - Creating methods inside a class
- Creating an object
- Accessing object attributes
- Calling object methods
2. Attributes and Methods
Classes can hold both data and code. These are categorized into instance-level and class-level members.Instance Methods
Functions inside a class that operate on a specific instance of that class. They must acceptself as the first argument.
Class Attributes & Methods (@classmethod)
- Class Attributes: Variables shared by all instances of a class.
- Class Methods: Decorated with
@classmethod, they acceptcls(the class itself) instead ofself. They are used for factory methods or modifying class-level state.
Static Methods (@staticmethod)
Decorated with @staticmethod, these do not accept self or cls. They act like normal helper functions grouped inside the class namespace.
Type Checking (type vs isinstance)
type(obj)returns the exact class/type of an object.isinstance(obj, ClassName)checks if an object is an instance of a class or any subclass (preferred for polymorphism).
3. Class Inheritance
Inheritance allows a new class (child/subclass) to inherit attributes and methods from an existing class (parent/superclass).Passing Arguments Along with Class Name in Inheritance
You can pass custom configuration arguments directly inside the class declaration parentheses next to the parent class name. This is done by implementing the special class method__init_subclass__ in the parent class.
What happens when this code is run?
- Class-level Interception: When Python compiles and executes the class definition of
UserProfile, it notices thatDatabaseModeldefines a__init_subclass__method. - Hook Execution: Instead of just creating the
UserProfileclass normally, Python automatically callsDatabaseModel.__init_subclass__(UserProfile, table="users"). - Property Assignment: The method receives the newly created subclass as
clsand the keyword argumenttable. It then setscls.table_name = "users". This operates at class-definition time (import time), long before any instances ofUserProfileare created.
Why do we need this pattern?
- Declarative Configuration: In ORM libraries (like SQLAlchemy or SQLModel) or API frameworks, it is common to define database tables or routes declaratively. This pattern allows subclasses to configure themselves during creation.
4. Encapsulation
Encapsulation restricts direct access to an object’s internal state to prevent accidental modifications.Private & Protected Fields
- Protected (
_name): A convention suggesting the field is for internal/subclass use. Python does not enforce this. - Private (
__pin): Triggers Name Mangling (_ClassName__pin), causing Python to raise anAttributeErrorif accessed directly.
5. Properties
Property Getters & Setters (@property)
Properties allow you to define methods that behave like attributes, which is useful for validating data when reading or writing a field.
6.Abstract Classes
Python provides built-in mechanisms to inspect objects at runtime, define interfaces/abstract classes, and customize how arguments are passed during class inheritance.Abstract Base Classes (ABCs)
Theabc module allows you to define abstract classes that cannot be instantiated and force subclasses to implement specific methods.
7. Introspection
Introspection: __dict__ and __annotations__
__dict__: A dictionary containing the namespaces of an object (its attributes and values).__annotations__: A dictionary containing type annotations defined on the class or function.
Type Annotation
A type annotation only specifies the expected type of an attribute. It does not create or initialize the attribute.name and price are only type hints.
Attempting to access them through the class results in an error.
Instance Variables
Instance variables are created when a value is assigned toself.
Class Variables
A class variable belongs to the class and is shared by all instances.Type Annotations for Class Variables
Class variables can also be annotated.Default Values
A default value provides an initial value for an instance attribute. For example, in Pydantic:The Ambiguity
Consider this declaration:In Plain Python
category is a class variable.
In Pydantic
category becomes an instance field with a default value.
This difference exists because Pydantic interprets annotated attributes as model fields.
Using ClassVar
To explicitly indicate that an attribute is a class variable, use ClassVar.
categoryis a class variable.nameis a model field.
ClassVar attributes when creating the model.
Comparison
Type Annotation vs Class Variable
Class Variable vs Default Value
Rule of Thumb
Plain Python
Pydantic
Explicit Class Variable (Recommended)
Using ClassVar makes your intent explicit and prevents frameworks like Pydantic and dataclasses from treating the attribute as an instance field.
Practice & Exercises
To reinforce what you’ve learned in this section (classes/instances, static/class methods, inheritance/init_subclass, encapsulation, properties, abstract base classes, and introspection), practice with these interactive notebooks:Follow-Along Practice
Practice class instantiation, defining instance/class/static methods, class inheritance, custom init_subclass hooks, protected/private encapsulation, properties, ABC templates, and instance/class introspection.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises including car factories, string parsers, department managers, secure bank accounts, notifications dispatchers, and class metadata scanners.💻 VS Code | 🚀 Colab | 📥 Download