Class in Python (with Examples)
In this tutorial, we will learn about class in Python with the help of real-time examples. In Python or any other object-oriented programming languages, classes are the fundamental feature of OOPs concept.
Classes provide a way to create objects that encapsulate data (attributes) and behavior (methods) held together into a single unit. After reading this tutorial, we will be able to create your own classes of objects. So, let’s start to understand the definition of class.
We know Python is an object-oriented programming language. An object-oriented programming (OOPs) provides a methodology or paradigm to design a program using classes and objects. The classes are the building blocks in the Python or any other programming language like Java.
According to OOPs, a class is a blueprint or template with which we create an object. When we create an object of the class data type, the object is called an instance of a class.
In Python, a class is user-defined data type like a list, string, dictionary, float, or an integer. It belongs to the data type “type”. A class is a set of data attributes that characterize any object of class.
The value that we store in an object is called data attribute, while the functions associated with it are called methods. Thus, a class in Python is a way of creating, organizing, and managing objects with a set of attributes and methods.
In simple words, a class contains data (i.e. data members) and methods that we can access or manipulate this data. Data members (variables) are visible in all the functions inside the class.
In Python or any other programming language, a class is a collection of as many as objects, which is common to all objects of one type. Let’s understand it with the help of real-time examples.
Realtime of Classes and Objects in Python
There are various real-time examples of classes and objects. They are as:
1. Imagine you’re in the market for a new mobile phone. Mobile phones come in various makes and models, each with its own unique features and specifications. With each passing day, various mobile companies launch new mobiles with latest features and versions.
Some of the latest features of mobiles are 5G connectivity, brand, model, colour, price, operating system (Android or iOS), camera quality, calling, text messaging, etc.
Now if we understand the whole scenario in the terms of OOPs, what will we find is that there is a mobile which can have different features. So, here, Mobile is a class and its features are objects which are represented as attributes and methods. These attributes and methods define the properties and behavior of a mobile phone.
2. Bird is a class and sparrow, pigeon, crow, parrot are objects of class Bird.
3. Vehicle is a class and bus, car, jeep are the objects of class Vehicle.
4. Player is a class and MS Dhoni, Sachin Tendulkar, and Virat Kohli are objects of class Player.
5. Flower is a class and rose, lily, lotus are objects of the class Flower.
6. Fruit is a class and mango, banana, apple are objects of class Fruit.
Remember that a class is generic in nature while an object is a specific in nature.
Examples of Built-in Classes in Python
Let us take some examples of built-in classes in Python to understand more clearly.
1. Python provides the “int” and “float” classes that we use to create integer and floating-point numbers. For example:
num = 20 # num is an object of int class. pi = 3.14 # pi is an object of float class.
2. Python provides a built-in “str” class that we use to create strings, which are sequences of characters. For example:
name = "Mahika" # name is an object of str class.
3. The “list” class is used to create lists, which are ordered collections of items or elements. For example:
num_list = [1, 2, 3, 4] # num_list is an object of list class
4. The built-in “tuple” class is used to create immutable sequences of items. For example:
tpl = ('a', 'b', 'c', 'd') # tpl is an object of tuple class
These are just a few examples of the many built-in classes in Python. Other examples of classes are bool, set, dict, file, etc. Each of these classes comes with its own set of methods and functionality to perform various operations. We can create objects of these classes to work with data in our programs.
How to Create a Class in Python?
To define or create a class in Python, use the keyword class, followed by a class name (identifier) and a colon. The general syntax to create a class definition is as follows:
class class_name:
"""document string"""
statement_1
statement_2
. . . . . .
statement_n
Syntax Description
In the above syntax, there are the following points that you should keep in mind while defining a class.
1. A class name must start with the uppercase by convention.
2. The class definition is usually followed by a document string called “docstring” which tells a short description of a class. However, it is optional in the class. We can access the doc string by using the following techniques:
- print(class_name.__doc__)
- help(class_name)
3. The class statement is a compound statement that contains doc string, data fields (i.e. attributes) to keep data and methods for defining behaviours. Attributes and methods simply represent normal variables and functions.
4. A class definition does not construct an object or instance of a class, but defines attributes that all objects of the class share.
5. In Python, every class contains a special method __init__() called initializers, which is the same as a constructor in the other object-oriented programming language, like Java. It first gets invoked automatically every time when we create a new object or new instance of a class.
6. Class definition usually places near the top of a module, after the import statements and global variables declaration.
7. When a class is loaded in the memory, Python interpreter executes the statements in the block.
8. We can also create a new class by deriving it from one or more existing classes. You will understand it in the further inheritance tutorial.
9. To define a null class, use the pass statement.
10. Data attributes that we apply to the whole class are defined first, and are class attributes or class variables.
11. Data attributes that we apply to a specific instance of the class (object) are called instance attributes or instance variables.
Simple Class Example Program in Python
Let’s take some simple example programs based on the definition of the class in Python.
Example 1:
class A:
"""Document Info"""
# Accessing and displaying docstring associated with class A.
print(A.__doc__)
help(A)
Output: Document Info Help on class A in module __main__: class A(builtins.object) | Document Info | | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)
In this example, we have defined a class named A. The class doesn’t contain any attributes or methods defined within it. However, there’s a docstring “Document Info” enclosed in triple quotes right below the class definition.
We use doc strings to provide a description of classes, functions, and modules in Python. Docstrings are used to describe what the class or function does.
We can access it using the .__doc__ attribute or help() function. This statement “print(A.__doc__)” displays the docstring associated with class A. It accesses the .__doc__ attribute of the class and prints its content. In this case, it will print “Document Info”.
Then, we have used help() function that return information about modules, classes, functions, and other objects. When we pass a class (or any object) as an argument to the help() function, it displays information about that object, including its docstring and a list of its attributes and methods.
Example 2:
class MyClass:
'''Python Class.'''
x = 10
def greet (self):
print ("Good morning!")
print(MyClass.x)
print(MyClass.greet)
print(MyClass.__doc__)
Output: 10 <function MyClass.greet at 0x00000203BFC2F400> Python Class.
In this example, we have defined a class named MyClass. This class contains a class attribute named x, whose value is set to 0. A class attribute shares among all instances of the class. The general syntax to access a class attribute or variable is as:
class_name.attribute_name
Using this syntax, we have accessed the class attribute as MyClass.x. The line MyClass.x prints the value of the class attribute x. Then, we have defined a greet() method that takes a self parameter. The parameter self refers to the reference instance of the class.
However, this method does not use the self parameter for any purpose within its implementation. The statement “print(MyClass.greet)” prints the memory address of method object MyClass.greet where the method is stored.
The statement “print(MyClass.__doc__)” prints the docstring associated with the class MyClass. The __doc__ attribute contains the docstring that we have defined within the class. This example illustrates accessing class attributes, displaying method objects, and retrieving the class docstring using the .__doc__ attribute.
Example 3:
class Animal:
def sound(self):
print("I am dog and sound bhow bhow")
def leg(self):
print("I have four legs")
# Creating an object of class Animal.
ani = Animal()
# Accessing both methods using reference variable ani.
ani.sound()
ani.leg()
Output: I am dog and sound bhow bhow I have four legs
In this example, we have defined a class named Animal that contains two methods: sound and leg. The sound() method prints a statement “I am a dog and sound bhow bhow”. The method uses the self parameter to refer to the reference instance of the class, although it doesn’t actually use any instance attributes in its implementation.
Similarly, the leg() method prints a statement “I have four legs”. Like the sound method, this method also uses the self parameter. Next, we have created an object (also known as an instance) of the Animal class. Then, we have called methods using dot (.) operator and reference variable ani.
Example 4:
class Person:
# Constructor declaration.
def __init__(self, name, age):
self.name = name
self.age = age
# Method declaration.
def introduce(self):
print(f"Hi, my name is {self.name} and I'm {self.age} years old.")
# Creating an instance of the Person class
person1 = Person("Alice", 25)
# Using methods of the Person class
person1.introduce()
Output: Hi, my name is Alice and I'm 25 years old.
In this example, we have defined a class named Person. This class has __init__() method (called constructor) that initializes the name and age attributes. It also contains a method introduce() that prints out an introduction message using the attributes.
Then, we have created an instance of the class. When Python interpreter executes this statement, the __init__() method is automatically called, initializing the name attribute to name parameter and the age attribute to age parameter.
Next, we have called introduce() method using the reference variable person1 to print an introduction message for that person. This example demos the basic structure of a class, constructor, attributes, and methods.
Example 5:
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
def get_value(self):
return self.value
# Creating an instance of the Counter class
counter1 = Counter()
# Using methods of the Counter class
print(counter1.get_value())
counter1.increment()
print(counter1.get_value())
counter1.increment()
print(counter1.get_value())
Output: 0 1 2
In this example, we have defined a class named Counter. This class contains __init__() method that initializes a value attribute to 0. It also contains two methods: increment() and get_value(). The increment method increments the value attribute by 1, and the get_value method returns the current value.
Then, we have created an object of the class Counter. When the Python interpreter will execute this statement, the __init__() method is automatically called, initializing the value attribute to 0.
Next, we have invoked the get_value() method using the reference variable counter1. The get_value method initially displays the value 0. Next, we have called the increment() method that increments by 1.
We have invoked this method twice to increment the value of variable and displayed the updated value using get_value() method. This example demos how the self parameter is used to access and modify the attributes of an instance within its methods.
Example 6:
class Student:
"""Student Info"""
def __init__(self):
self.name = "Alice"
self.age = 20
def display(self):
print("Name:", self.name)
print("Age:", self.age)
# Creating an instance of the Student class.
st = Student()
# Calling the display method using the reference variable st.
st.display()
Output: Name: Alice Age: 20
In this example, we have defined a class named Student. It has a docstring “””Student Info””” that provides a brief description of the class.
Inside the class, we have defined a special method named __init__. This method is the constructor and is called when we will create an object of the class. Inside the method, we have initialized the instance attributes, such as name and age, using self reference. The self parameter refers to the instance being created.
We have defined the display() method within the class. It prints out the student’s name and age using the self parameter to access the instance attributes.
Then, we have created an instance named st of the Student class. When this statement is executed by Python interpreter, the __init__() method is automatically called, initializing the name attribute to “Alice” and the age attribute to 20. Next, we have invoked the display() method using reference variable st.
In this tutorial, we have explained class in Python with the real-time example. Then, we have explained how to create a class in Python with the help of various examples. Hope that you will have understood the basic points of defining a class. Stay tuned with the next tutorial where you will learn what is an object in Python with the help of realtime examples.
Thanks for reading!!!