One of the essential concepts in object-oriented programming in Python is classes and objects. This article will provide an overview of these concepts, along with inheritance, their creation, and usage through an extended class example.
Table of Contents
Python Classes
A class is a template or design for multiple objects that share similar characteristics and behaviors. It consists of data attributes (variables) and methods (functions). Use the `class’ keyword followed by the name of the class and its indented contents to create a class in Python:
class User:
def __init__(self, name, email):
self.name = name
self.email = email
In this example, we have created a User
class with two attributes (name
and email
) initialized in the __init__()
method, also known as the constructor.
Python Objects
An object is an instance of a class. It is created by calling the class name using parentheses and passing arguments to its constructor:
michael_monroe = User("Michael Monroe", "michael.monroe@example.com")
print(f"Name: {michael_monroe.name}, Email: {michael_monroe.email}")
In this example, we have created an object michael_monroe
of the User
class and accessed its attributes using dot notation (.
).
Class Methods
A method is a function defined within a class that operates on the class’s objects. It can access and modify the data attributes of the object it is called upon:
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def say_hello(self):
print(f"Hello, {self.name}!")
In this example, we have added a say_hello()
method to our User
class that prints a greeting using the object’s name
attribute.
Inheritance
Inheritance allows us to create new classes based on existing ones, inheriting their attributes and methods. This is achieved by using the keyword `class’ followed by the name of the class with a colon and the name of the parent class in brackets:
class Customer(User):
def __init__(self, name, email):
super().__init__(name, email)
self.is_customer = True
In this example, we have created a Customer
class that inherits from the User
class. The super()
function calls the parent class’s constructor to initialize its attributes.
Extended Class Example
Let’s create an extended customer class with a calculation function for customer turnover:
class Customer(User):
def __init__(self, name, email):
super().__init__(name, email)
self.is_customer = True
self.purchases = []
def add_purchase(self, product, price):
self.purchases.append((product, price))
def get_total_spent(self):
total = sum([price for _, price in self.purchases])
return f"{self.name} has spent {total:,.2f}"
sarah_mueller = Customer("Sarah Mueller", "sarah.mueller@example.com")
sarah_mueller.add_purchase("T-Shirt", 20)
sarah_mueller.add_purchase("Jean", 80)
print(f"Name: {sarah_mueller.name}, Total Spent: {sarah_mueller.get_total_spent()}")
This example adds a purchases
list attribute and an add_purchase()
method to our base User
class. We have also added a get_total_spent()
method that calculates the total spent by the customer. The Customer
class inherits from this extended User
class.
In conclusion, Python classes and objects provide an effective way of organizing code in object-oriented programming. Inheritance allows for reusability and flexibility when creating new classes based on existing ones. By understanding these concepts and their creation and usage, developers can create more maintainable and scalable applications using Python.