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: Class Definitions in Python
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

Class Definitions in Python

Last updated: Nov 28, 2023 11:42 pm
By Harsh S.
Share
10 Min Read
Class Definitions in Python
SHARE

In this tutorial, we’ll explore the basics of class definitions in Python. A class is like a template for making specific objects. It outlines the characteristics and actions shared by all objects of that type. Classes help organize code, making it easier to reuse and manage.

Contents
1. Simple Class Definition2. Class Methods3. Class Variables4. Inheritance5. Polymorphism6. Unique Example Code Snippets7. Comparing Class Definitions in PythonWhich Method Is the Most Suitable?

How to Begin with Class Definitions in Python

To define a class in Python, you use the class keyword. The class definition must include the class name and a colon (:) next to it. The body of the class definition uses indentation and contains the properties and behaviors of the class.

Must Read: How to Create a Class in Python

1. Simple Class Definition

Here is an example of a simple class definition:

Python code:

class Pen:
    def __init__(self, make, color):
        self.make = make
        self.color = color

    def write(self):
        print(f"The {self.make} pen has {self.color} ink.")

This class defines a Pen object with two properties: make and color. It also defines a method called write(), which prints a message to the console.

You can make a Pen class instance by calling the class in the same way you do with a function. For example, the following code creates a fresh Pen object named my_pen:

Python code:

my_pen = Pen("Pilot", "Blue")

You can then access the properties and methods of the my_pen object using the dot notation. For example, the following code prints the make of the pen to the console:

Python code:

print(my_pen.make)

You can also call the write() method to make the pen write:

Python code:

my_pen.write()

2. Class Methods

Class methods a.k.a. special methods that belong to the class itself, rather than to individual instances of the class. Their main purpose is to perform operations that are common to all objects of the class, such as creating new objects or validating input.

To define a class method, you use the @classmethod decorator. For example, the following code defines a class method called create(), which creates a fresh Pen object from a given name and breed:

Python code:

class Pen:
    @classmethod
    def create(cls, make, color):
        return cls(make, color)

To call a class method, you use the dot notation and the class name. For example, the following code creates a fresh Pen object named another_pen using the create() class method:

Python code:

another_pen = Pen.create("Hauser", "Green")

3. Class Variables

Class variables are variables that belong to the class itself, rather than to individual instances of the class. They store information that is common to all objects of the class, such as the number of objects created. up to a certain point.

To define a class variable, you use the @classmethod decorator. For example, the following code defines a class variable called num_pens, which stores the number of Pen objects that have been created:

Python code:

class Pen:
    num_pens = 0

    def __init__(self, make, color):
        self.make = make
        self.color = color
        Pen.num_pens += 1

The num_pens class variable is incremented each time a new Pen object is created. To access the num_pens class variable, you use the dot notation and the class name. For example, the following code prints the number of Pen objects created in the console:

Python code:

print(Pen.num_pens)

Also Read: Python Multiple Inheritance

4. Inheritance

Inheritance is a mechanism that allows new classes to be created by deriving from existing classes. Such classes called the subclass, inherit all of the properties and behaviors of the existing class, called the base class.

To define a subclass, you use the class keyword and the name of the base class, separated by a colon (:). For example, the following code defines a subclass of the Pen class called Ballpoint:

Python code:

class Ballpoint(Pen):
    pass

The Ballpoint class inherits all of the properties and behaviors of the Pen class. This means that you can create Ballpoint objects in the same way that you create Pen objects. You can also access the properties and methods of Ballpoint objects in the same way that you access the properties and methods of Pen objects.

5. Polymorphism

Polymorphism is a mechanism that allows objects of different types to respond to the same method call in different ways. For example, the following code defines a method called write() that can be called on both Pen and Ballpoint objects:

Python code:

class Pen:
    def __init__(self, make, color):
        self.make = make
        self.color = color

    def write(self):
        print(f"The {self.make} pen has {self.color} ink.")

    @classmethod
    def create(cls, make, color):
        return cls(make, color)

class Ballpoint(Pen):
    def write(self):
        print(f"The {self.make} Ballpoint pen has {self.color} ink.")

pen = Pen.create("Hauser", "Red")
point = Ballpoint.create("Linc", "Orange")

# Call the write() method on both the pen and the point
pen.write()
point.write()

Output:

The Hauser pen has Red ink.
The Linc Ballpoint pen has Orange ink.

The write() method is overridden in the Ballpoint class, so when it is called on a Ballpoint object, the Ballpoint version of the method is executed. This is an example of polymorphism.

6. Unique Example Code Snippets

Here is a unique example of a class definition using variables and function names that are short and unique, and do not include words like Alice, Wonderland, city, age, or name:

Python code:

class Fan:
    fan_count = 0  # Class variable to keep track of the number of fans

    def __init__(self, brand, type):
        self.brand = brand
        self.type = type
        self.is_on = False
        Fan.fan_count += 1  # Increment the fan count upon instance creation

    def turn_on(self):
        if not self.is_on:
            self.is_on = True
            print(f"The {self.brand} {self.type} fan is now turned on.")
        else:
            print(f"The {self.brand} {self.type} fan is already on.")

    def turn_off(self):
        if self.is_on:
            self.is_on = False
            print(f"The {self.brand} {self.type} fan is now turned off.")
        else:
            print(f"The {self.brand} {self.type} fan is already off.")

    def display_info(self):
        print(f"Brand: {self.brand}, Type: {self.type}, Is On: {self.is_on}")

# Create a Fan instance
my_fan = Fan("Dyson", "Tower")

# Turn on the fan
my_fan.turn_on()

# Try to turn on the same fan again
my_fan.turn_on()

# Turn off the fan
my_fan.turn_off()

# Display fan information
my_fan.display_info()

# Output the total number of fans created
print(f"Total number of fans: {Fan.fan_count}")

Output:

The Dyson Tower fan is already on.
The Dyson Tower fan is now turned off.
Brand: Dyson, Type: Tower, Is On: False
Total number of fans: 1

7. Comparing Class Definitions in Python

MethodDescriptionMost Suitable For
Class methodsA class method is owned by the class itself, not by individual class instances. People generally use class methods for tasks that apply universally to all objects of the class, such as creating new objects or checking input validity.Carrying out operations that all class objects commonly share.
Class variablesClass variables represent data owned by the class as a whole, not tied to specific instances. They are typically employed to hold shared information across all objects of the class, like the count of created objects.Storing data that all class objects share in common.
InheritanceInheritance enables the creation of new classes by deriving from existing classes. The subclass, which is the new class, inherits all the properties and behaviors of the base class, which is the existing class.Creating new classes that adopt the properties and behaviors of an existing class.
PolymorphismPolymorphism permits objects of various types to react differently when the same method is invoked.Enabling objects of various types to react differently when the same method is called.
Comparing Python Class Definitions

Which Method Is the Most Suitable?

The most suitable method to use depends on the specific needs of your program. However, here are some general guidelines:

  • Use class methods to perform operations that are common to all objects of the class.
  • Use class variables to store information that is common to all objects of the class.
  • Use inheritance to create new classes that share the properties and behaviors of an existing class.
  • Use polymorphism to allow objects of different types to respond to the same method call in different ways.

Conclusion

Class definitions are a powerful way to organize your code and make it more reusable and maintainable. By using class methods, class variables, inheritance, and polymorphism, you can create complex and sophisticated programs.

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

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Higher Order Functions in Python Code Higher Order Functions in Python
Next Article Python String Strip Basics Python String Strip Tutorial

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