This Python class tutorial covers class creation, attributes, and methods with self-explanatory examples for hands-on learning. We have added self-explanatory examples so that you can quickly start coding your classes and take our help as needed.
During this tutorial, we’ll tell you what the “self” keyword is, what different attributes a class can have, and how to define constructors for initialization purposes.
You’ll also get to know how inheritance works in Python, how it deals with multiple inheritance and what is operator overloading. Let’s dive in.
Get Started with Classes and Objects in Python
Yes, Python supports object-oriented programming (OOP). OOP is a development model which lets a programmer focus on producing reusable code. It is different from the procedural model which follows a sequential approach.
OOP is useful when you have a large and complicated project to work on. There will be multiple programmers creating reusable code, and sharing and integrating their source code. Reusability results in better readability and reduces maintenance in the longer term.
What is a Class in Python?
A class is an arrangement of variables and functions into a single logical entity. It works as a template for creating objects. Every object can use class variables and functions as its members.
Python has a reserved keyword known as “class” which you can use to define a new class.
The object is a working instance of a class created at runtime.
Also Read: Class Definitions in Python
How to Create Classes in Python
To create a class, you should follow the below structure. After that, it will be quite easy to create your own Python classes.
class ClassName: """Class documentation.""" # Class Attributes def __init__(self, arguments): """Constructor.""" # Initialize Class Attributes # Class Methods
There are some terms that you need to know while working with classes in Python.
1. The “class” keyword
2. The instance attributes
3. The class attributes
4. The “self” keyword
5. The “__init_” method
Let’s now have a clear understanding of each of the above points one by one.
The “class” keyword
With the class keyword, we can create a class as shown in the example below.
class BookStore: pass
Also Read: Data Classes in Python 3
The “self” keyword
Python provides the “self” keyword to represent the instance of a class. It works as a handle for accessing the class members such as attributes from the class methods.
Also, please note that it is implicitly the first argument to the __init__ method in every class. You can read about it below.
__init__ (constructor)
The “__init__()” is a unique method associated with every Python class.
Python calls it automatically for every object created from the class. Its purpose is to initialize the class attributes with user-supplied values.
It is commonly known as Constructor in object-oriented programming. See the below example.
class BookStore: def __init__(self): print("__init__() constructor gets called...") B1 = BookStore()
Output
__init__() constructor gets called...
The instance attributes
These are object-specific attributes defined as parameters to the __init__ method. Each object can have different values for themselves.
In the below example, the “attrib1” and “attrib2” are the instance attributes.
class BookStore: def __init__(self, attrib1, attrib2): self.attrib1 = attrib1 self.attrib2 = attrib2
The class attributes
Unlike the instance attributes which are visible at object-level, the class attributes remain the same for all objects.
Check out the below example to demonstrate the usage of class-level attributes.
class BookStore: instances = 0 def __init__(self, attrib1, attrib2): self.attrib1 = attrib1 self.attrib2 = attrib2 BookStore.instances += 1 b1 = BookStore("", "") b2 = BookStore("", "") print("BookStore.instances:", BookStore.instances)
In this example, the “instances” is a class-level attribute. You can access it using the class name. It holds the total number of instances created.
We’ve created two instances of the class <Bookstore>. Hence, executing the example should print “2” as the output.
# output BookStore.instances: 2
Python Class Method
The class methods are methods that directly link to the class rather than its object. This means that we can call them without requiring the creation of an object from the class.
1. Defining a class method
To define a class method, you use the @classmethod
decorator just above the method definition.
The first parameter of a class method is traditionally named cls
which refers to the class itself.
2. Accessing class attributes
Class methods can access and modify class-level attributes (variables that are shared among all instances of the class).
They can’t access or modify instance-specific attributes (attributes unique to each object).
3. When to use a class method
Here are some common use cases where the Python class method becomes useful for us.
Also Read: Python Static Method
Modify the class state. For example, a class method could be used to increment a class variable or to add a new item to a class list.
@classmethod def get_instance_count(cls): return cls.instance_count
Perform factory operations. For example, a class method could be used to create a new object of the class with specific values for its attributes.
@classmethod def create_employee(cls, name, position): if position == 'manager': return cls(name, 80000) else: return cls(name, 50000)
Alternative constructors. For example, we might have a class representing dates and use a class method to create instances from a string in a specific format.
@classmethod def from_string(cls, date_str): year, month, day = map(int, date_str.split('-')) return cls(year, month, day)
4. Invoking class methods
- Class methods are called on the class itself, not on instances of the class.
- You can call them using the class name,
ClassName.method()
rather thanobject.method()
.
Here’s a practical example of a Python class method:
class MyClass: instance_count = 0 # Class-level attribute def __init__(self, data): self.data = data MyClass.instance_count += 1 @classmethod def get_instance_count(cls): return cls.instance_count # Creating instances obj1 = MyClass(10) obj2 = MyClass(20) # Calling the class method to get the instance count count = MyClass.get_instance_count() print(f"Number of instances created: {count}") # Output: Number of instances created: 2
In this example, the get_instance_count()
is a class method that returns the count of instances. It demonstrates one of the practical uses of class methods.
Also Read: Data Class Exercises
Examples of Python Classes
Given here is a Python class example where we defined a BookStore class. It has a constructor to initialize the members and a class method to print the details. We created three objects with different values.
Create a BookStore class in Python
class BookStore: noOfBooks = 0 def __init__(self, title, author): self.title = title self.author = author BookStore.noOfBooks += 1 def bookInfo(self): print("Book title:", self.title) print("Book author:", self.author,"\n") # Create a virtual book store b1 = BookStore("Great Expectations", "Charles Dickens") b2 = BookStore("War and Peace", "Leo Tolstoy") b3 = BookStore("Middlemarch", "George Eliot") # call member functions for each object b1.bookInfo() b2.bookInfo() b3.bookInfo() print("BookStore.noOfBooks:", BookStore.noOfBooks)
You can open IDLE or any other Python IDE, save the above code in some file, and execute the program.
In this example, we have created three objects of the BookStore class, i.e., b1, b2, and b3. Each of the objects is an instance of the BookStore class.
UML diagram of BookStore class
The UML diagram of the above code is as follows.
After executing the code in the example, you should see the following result.
# output Book title: Great Expectations Book author: Charles Dickens Book title: War and Peace Book author: Leo Tolstoy Book title: Middlemarch Book author: George Eliot BookStore.noOfBooks: 3
You might have observed from the above example that we’ve used a few keywords like “self” and “__init__.”
Here are some simple Python class and object exercises for practicing object-oriented programming in Python. However, once you complete this tutorial, check out our 40 basic Python exercises for beginners.
Exercise-1
Create a class called SavingsAccount that represents an actual savings account in a bank. It has two properties: funds and rate_of_interest. The class should also have a method debit() that decreases the funds by the specified amount and a method credit() that adds to the existing balance. Also, define a third method to transfer the interest amount to the savings account.
Python Code:
class SavingsAccount: def __init__(self, funds, rate_of_interest): self.funds = funds self.rate_of_interest = rate_of_interest def debit(self, value): self.funds -= value def credit(self, value): self.funds += value def transfer_interest(self): self.funds *= 1 + self.rate_of_interest
Exercise-2
Create a class called Product that has two properties: name and price. The class should also have a method get_total_cost() that returns the total cost (1.5 times the price) of the product, including tax.
Python Code:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def get_total_cost(self):
return self.price * 1.5
Exercise-3
Define a class called ShoppingCart that has a list of products. The class should also have a method called add_product() that adds a product to the shopping cart and a method called get_total_cost() that returns the total cost of all the products in the shopping cart.
Python Code:
class ShoppingCart: def __init__(self): self.products = [] def add_product(self, product): self.products.append(product) def get_total_cost(self): total_cost = 0 for product in self.products: total_cost += product.get_total_cost() return total_cost
Exercise-4
Create a class called Product that represents products with attributes: prod_id, name, price, and quantity. Then, create a class called Company to manage product inventory.
- Product class:
- Contains the product details.
- Allows setting product details and retrieving them.
- Company class:
- Manages a list of products.
- Can add products to the inventory.
- Can remove products from the inventory.
- Can list all products in the inventory.
- Can calculate the total value of the inventory.
- Implement error handling for unique product_id values and when removing non-existent products.
Python Code:
class Product: def __init__(self, prod_id, name, price, quant): self.prod_id = prod_id self.name = name self.price = price self.quant = quant class Company: def __init__(self): self.products = [] def add(self, product): if product.prod_id not in [p.prod_id for p in self.products]: self.products.append(product) else: print(f"Product with ID {product.prod_id} already exists.") def remove(self, prod_id): for product in self.products: if product.prod_id == prod_id: self.products.remove(product) return print(f"Product with ID {prod_id} not found.") def list(self): for product in self.products: print(f"Product ID: {product.prod_id}, Name: {product.name}, Price: ${product.price}, Quantity in Stock: {product.quant}") def total_value(self): return sum(product.price * product.quant for product in self.products)
Exercise-5
Implement a class called Company that has a list of employees. The class should also have a method called total_sal() that returns the total salary of all the employees in the company.
Python Code:
class Employee: def __init__(self, name, sal): self.name = name self.sal = sal class Company: def __init__(self): self.emps = [] def add(self, emp): if isinstance(emp, Employee): self.emps.append(emp) def total_sal(self): return sum(emp.sal for emp in self.emps) # Usage example: if __name__ == "__main__": company = Co() emp1 = Employee("Eva", 50000) emp2 = Employee("Leo", 60000) emp3 = Employee("Max", 75000) company.add(emp1) company.add(emp2) company.add(emp3) total = company.total_sal() print(f"Total Salary of all employees: ${total}")
Summary: Python Classes, Objects, and Methods
Today, we have covered the basics of classes, objects, and methods in Python with self-explanatory examples. Let’s summarize quickly our learnings from this tutorial.
Classes:
Objects:
Class methods:
Additional technical facts:
In the next tutorials, you will see topics like Python multiple inheritance and method overloading.
Keep Learning!
TechBeamers