13. Python Classes and Objects
Python Classes and Objects
Python is an Object-Oriented Programming (OOP) language. Almost everything in Python is an object, meaning it has properties (data) and methods (actions it can perform). A Class is like an object constructor, or a blueprint for creating objects.
Instead of writing messy, disconnected variables and functions, classes allow you to group related data and functions together into a single organized entity. This makes your code modular, reusable, and much easier to maintain.
Creating a Class
To create a class, use the keyword class. By convention, class names in Python always start with a capital letter (PascalCase).
Creating an Object
Once you have a class (the blueprint), you can use it to build actual objects. This process is called instantiation. You create an object by calling the class name as if it were a function.
The __init__() Function
To understand the true power of classes, you must master the built-in __init__() function. All classes have this function, which is always executed automatically exactly when the class is being initiated.
Use the __init__() function to assign initial values to object properties.
The __str__() Function
The __str__() function controls what should be returned when the class object is represented as a string. If you do not define it, printing the object just gives you a cryptic memory address.
Object Methods
Objects can also contain methods. Methods in objects are simply functions that belong to the object. They define the actions the object can perform.
The self Parameter
The self parameter is a reference to the current instance of the class. It is used to access variables and methods that belong to the class.
It absolutely must be the first parameter of any instance method in the class.
Modifying Object Properties
You can easily modify properties on objects after they have been created using standard dot notation.
Deleting Object Properties
If you no longer need a property on a specific object instance, you can delete it using the del keyword.
Deleting Objects Entirely
You can also delete an entire object outright if you are completely finished with it. Use the del keyword followed by the object name.
The pass Statement in Classes
Class definitions cannot be empty. If you are scaffolding out an application and need a class structure but have no content for it yet, put in the pass statement.
Knowledge Check
Ready to test your understanding of 13. Python Classes and Objects?