Classes and Objects
Python is a language with support for object-oriented programming. This means you can model real-world elements as objects that have properties (attributes) and behaviors (methods), using classes as a blueprint to create them.
What is a Class?
Section titled “What is a Class?”A class is a template or blueprint used to create objects (instances). It groups data and functions that operate on that data.
class Product:passIn this example, Product is the name of the class. For now, it has no attributes or methods.
The __init__ Method
Section titled “The __init__ Method”The special method __init__ is the constructor of the class. It is automatically executed when you create a new instance (object) and is used to initialize the object’s attributes.
class Product:def __init__(self, name, price):self.name = nameself.price = priceWhen you create a new product with Product("Shoe", 50), the __init__ method assigns "Shoe" to self.name and 50 to self.price.
The self Parameter
Section titled “The self Parameter”self is a reference to the object itself. It is used within the class’s methods to access or modify the attributes and to call other methods of the same object. It must always be the first parameter of any instance method, although you do not pass it explicitly when calling the method.
class Product:def display_info(self):print(self.name, self.price)When you call p.display_info(), Python automatically passes the object p as an argument for self.
Complete Example
Section titled “Complete Example”Let’s see a complete example of how to define a class, create an object, and use its methods:
class Product:def __init__(self, name, price):self.name = nameself.price = price
def display_info(self):print(f'Product: {self.name} | Price: ${self.price}')
# Create an objectp1 = Product('Shirt', 25.99)
# Use the methodp1.display_info()Output:
Product: Shirt | Price: $25.99Summary
Section titled “Summary”- A class is a blueprint for creating objects.
- The
__init__method initializes the object’s attributes. - The
selfparameter allows access to the object’s attributes and methods. - You can create multiple objects from the same class, each with its own values.
Ready to create your own classes and objects? Practice modifying the examples!