TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Classes and Methods: A Quick Ref Guide
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python OOPPython Tutorials

Python Classes and Methods: A Quick Ref Guide

Last updated: Apr 20, 2024 11:42 am
By Meenakshi Agarwal
Share
15 Min Read
Python Class & OOP Fundamentals
Python Class & OOP Fundamentals
SHARE

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.

Contents
What is a Class in Python?How to Create Classes in PythonThe “class” keywordThe “self” keyword__init__ (constructor)The instance attributesThe class attributesPython Class Method1. Defining a class method2. Accessing class attributes3. When to use a class method4. Invoking class methodsExamples of Python ClassesCreate a BookStore class in PythonUML diagram of BookStore classExercise-1Exercise-2Exercise-3Exercise-4Exercise-5Summary: Python Classes, Objects, and Methods

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 clswhich 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 than object.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.

Python Class and Objects (UML diagram)
UML diagram – Depicting BookStore class and objects

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:

  • Classes are defined using the class keyword.
  • Classes can have attributes and methods.
  • Attributes are class-specific variables.
  • Methods are functions that bind to the class.
  • Classes can be inherited from other classes.
  • Inheritance allows you to reuse code and create more specialized classes.

Objects:

  • Objects are created from classes using the new keyword.
  • Objects have their own copies of the class attributes.
  • They can call the class methods.
  • We can pass them as arguments to functions and return from functions.
  • We can compare them to other objects using the <, >, <=, >=, ==, and != operators.

Class methods:

  • Class methods bind to the class, not its objects.
  • Class methods call directly on the class, without creating an instance of the class first.
  • Class methods typically modify the class state, perform factory operations, or provide utility functions for the class.
  • Developers define class methods using the @classmethod decorator or the classmethod() function.

Additional technical facts:

  • Classes are first-class objects, we can pass them as arguments and return from functions.
  • Classes can nest inside another class.
  • Subsequently, they can create metaclasses, which creates other classes.

In the next tutorials, you will see topics like Python multiple inheritance and method overloading.

Keep Learning!
TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Tuple - Learn with Examples Python Tuple – A Tutorial to Get Started Quickly
Next Article Python Inheritance & OOP Concepts Python Inheritance in Classes

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x