Python Classes and Objects
Python follows the object-oriented programming (OOP) paradigm.
In Python, almost everything is an object, and every object contains:
- Attributes (data)
- Methods (functions)
A class acts as a template or blueprint used to create objects.
Creating a Class
To define a class in Python, use the class keyword followed by the class
name.
Example: Define a Simple Class
Output:
Here:
Bookis the classpagesis a class attribute
Creating Objects from a Class
Once a class is defined, you can create objects (instances) from it.
Example: Create an Object and Access a Property
Output:
Creating Multiple Objects
You can create any number of objects from the same class.
Each object is a separate instance but follows the same class structure.
Example: Multiple Objects from One Class
Output:
250
250
Object Independence
Although objects are created from the same class, they are independent of each other.
Changes made to one object do not automatically affect the others (unless using shared class variables intentionally).
Deleting Objects
Python allows you to delete objects using the del keyword.
After deletion, the object can no longer be accessed.
Example: Delete an Object
Output:
Attempting to use device after deletion will result in an error.
The pass Statement in Classes
A class definition cannot be empty.
If you need a class without content (for planning or future use), use the
pass statement.
