PYnative Python
PYnative Python
This Python OOP series contains the following in-depth tutorial. You can directly read those.
An object-oriented paradigm is to design the program using classes and objects. Python
programming language supports different programming approaches like functional programming,
modular programming. One of the popular approaches is object-oriented programming (OOP) to
solve a programming problem is by creating objects
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython%2Fobject-oriented-programming%2F 1/8
8/8/22, 8:13 PM Python Object-Oriented Programming (OOP)
Attribute
Behavior
One important aspect of OOP in Python is to create reusable code using the concept of inheritance.
This concept is also known as DRY (Don't Repeat Yourself).
For example, you are creating a vehicle according to the Vehicle blueprint (template). The plan
contains all dimensions and structure. Based on these descriptions, we can construct a car, truck,
bus, or any vehicle. Here, a car, truck, bus are objects of Vehicle class
A class contains the properties (attribute) and action (behavior) of the object. Properties represent
variables, and the methods represent actions. Hence class includes both variables and methods.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython%2Fobject-oriented-programming%2F 2/8
8/8/22, 8:13 PM Python Object-Oriented Programming (OOP)
Object is an instance of a class. The physical existence of a class is nothing but an object. In other
words, the object is an entity that has a state and behavior. It may be any real-world object like the
mouse, keyboard, laptop, etc.
Instance method: Used to access or modify the object attributes. If we use instance
variables inside a method, such methods are called instance methods.
Class method: Used to access or modify the class state. In method implementation, if
we use only class variables, then such type of methods we should declare as a class
method.
Static method: It is a general utility method that performs a task in isolation. Inside this
method, we don’t use instance or class variable because this static method doesn’t have
access to the class attributes.
Read Python Class Method vs. Static Method vs. Instance Method to understand the difference
between all three class methods.
The docstring is not mandatory but recommended to use. We can get docstring using __doc__
attribute. Use the following syntax to create a class.
Syntax
class classname:
'''documentation string'''
class_suite
Run
We can create any number of objects of a class. use the following syntax to create an object of a
class.
reference_variable = classname()
Run
class Employee:
# class variables
# instance variables
self.name = name
self.salary = salary
# instance method
def show(self):
emp1.show()
emp2.show()
Run
Output:
Employee: Harry 12000 ABC Company
Constructors in Python
In Python, a constructor is a special type of method used to initialize the object of a Class. The
constructor will be executed automatically when the object is created. If we create three objects, the
constructor is called three times and initialize each object.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython%2Fobject-oriented-programming%2F 4/8
8/8/22, 8:13 PM Python Object-Oriented Programming (OOP)
The main purpose of the constructor is to declare and initialize instance variables. It can take at
least one argument that is self. The __init()__ method is called the constructor in Python. In other
words, the name of the constructor should be __init__(self).
A constructor is optional, and if we do not provide any constructor, then Python provides the
default constructor. Every class in Python has a constructor, but it's not required to define it.
Read More:
Encapsulation in Python
In Python, encapsulation is a method of wrapping data and functions into a single entity. For
example, A class encapsulates all the data ( methods and variables). Encapsulation means the
internal representation of an object is generally hidden from outside of the object's definition.
Python Encapsulation
Need of Encapsulation
Encapsulation acts as a protective layer. We can restrict access to methods and variables from
outside, and It can prevent the data from being modified by accidental or unauthorized
modification. Encapsulation provides security by hiding the data from the outside world.
In Python, we do not have access modifiers, such as public, private, and protected. But we can
achieve encapsulation by using prefix single underscore and double underscore to control access
of variable and method within the Python program.
class Employee:
# public member
self.name = name
# private member
self.__salary = salary
def show(self):
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython%2Fobject-oriented-programming%2F 5/8
8/8/22, 8:13 PM Python Object-Oriented Programming (OOP)
emp.show()
print(emp.__salary)
Run
Output:
Name is Jessa and salary is 40000
In the above example, we create a class called Employee. Within that class, we declare two variables
name and __salary. We can observe that the name variable is accessible, but __salary is the private
variable. We cannot access it from outside of class. If we try to access it, we will get an error
Polymorphism in Python
Polymorphism in OOP is the ability of an object to take many forms. In simple words,
polymorphism allows us to perform the same action in many different ways.
Polymorphism is taken from the Greek words Poly (many) and morphism (forms). Polymorphism
defines the ability to take different forms.
For example, The student can act as a student in college, act as a player on the ground, and as a
daughter/brother in the home. Another example in the programming language, the + operator, acts
as a concatenation and arithmetic addition.
Python Polymorphism
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython%2Fobject-oriented-programming%2F 6/8
8/8/22, 8:13 PM Python Object-Oriented Programming (OOP)
Polymorphism with class methods is useful when we want objects to perform the same action in
different ways. In the below example, both objects calculate the area (same action) but in a
different way (different formulas)
class Circle:
pi = 3.14
self.radius = redius
def calculate_area(self):
class Rectangle:
self.length = length
self.width = width
def calculate_area(self):
# function
def area(shape):
# call action
shape.calculate_area()
# create object
cir = Circle(5)
rect = Rectangle(10, 5)
area(cir)
area(rect)
Run
Output:
Area of circle : 78.5
Area of Rectangle : 50
Inheritance In Python
In an Object-oriented programming language, inheritance is an important aspect. In Python,
inheritance is the process of inheriting the properties of the parent class into a child class.
The primary purpose of inheritance is the reusability of code. Using inheritance, we can use the
existing class to create a new class instead of recreating it from scratch.
Syntax
class BaseClass:
class DerivedClass(BaseClass):
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython%2Fobject-oriented-programming%2F 7/8
8/8/22, 8:13 PM Python Object-Oriented Programming (OOP)
In inheritance, the child class acquires all the data members, properties, and functions of the parent
class. Also, a child class can customize any of the parent class methods.
# Base class
class Vehicle:
self.name = name
self.color = color
self.price = price
def info(self):
# Child class
class Car(Vehicle):
car.info()
car.change_gear(5)
Run
Output:
BMW X1 Black 35000
Next Steps
Python OOP Exercise
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython%2Fobject-oriented-programming%2F 8/8
8/8/22, 8:14 PM Classes and Objects in Python
Objects have two characteristics: They have states and behaviors (object has attributes and methods
attached to it) Attributes represent its state, and methods represent its behavior. Using its methods,
we can modify its state.
For example, If we design a class based on the states and behaviors of a Person, then States can be
represented as instance variables and behaviors as class methods.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 1/10
8/8/22, 8:14 PM Classes and Objects in Python
Class: Person
Using the above class, we can create multiple objects that depict different states and behavior.
Object 1: Jessa
State:
Name: Jessa
Sex: Female
Profession: Software Engineer
Behavior:
Object 2: Jon
State:
Name: Jon
Sex: Male
Profession: Doctor
Behavior:
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 2/10
8/8/22, 8:14 PM Classes and Objects in Python
As you can see, Jessa is female, and she works as a Software engineer. On the other hand, Jon is a
male, and he is a lawyer. Here, both objects are created from the same class, but they have
different states and behaviors.
Syntax
class class_name:
<statement 1>
<statement 2>
<statement N>
Run
In this example, we are creating a Person Class with name, sex, and profession instance variables.
class Person:
self.name = name
self.sex = sex
self.profession = profession
def show(self):
def work(self):
A constructor is a special method used to create and initialize an object of a class. This method is
defined in the class.
In Python, Object creation is divided into two parts in Object Creation and Object initialization
And, using the __init__() method we can implement constructor to initialize the object.
Syntax
<object-name> = <class-name>(<arguments>)
Run
self.name = name
self.sex = sex
self.profession = profession
def show(self):
def work(self):
# call methods
jessa.show()
jessa.work()
Run
Output:
Name: Jessa Sex: Female Profession: Software Engineer
Class Attributes
When we design a class, we use instance variables and class variables.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 4/10
8/8/22, 8:14 PM Classes and Objects in Python
Objects do not share instance attributes. Instead, every object has its copy of the instance attribute
and is unique to each object.
All instances of a class share the class variables. However, unlike instance variables, the value of a
class variable is not varied from object to object.
Only one copy of the static variable will be created and shared between all objects of the class.
Example
class Student:
# class variables
# constructor
# instance variables
self.name = name
self.age = age
s1 = Student("Harry", 12)
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 5/10
8/8/22, 8:14 PM Classes and Objects in Python
s1.name = 'Jessa'
s1.age = 14
Output
Student: Harry 12
Student: Jessa 14
Class Methods
In Object-oriented programming, Inside a Class, we can define the following three types of
methods.
Instance methods work on the instance level (object level). For example, if we have two objects
created from the student class, They may have different names, marks, roll numbers, etc. Using
instance methods, we can access and modify the instance variables.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 6/10
8/8/22, 8:14 PM Classes and Objects in Python
A class method is bound to the class and not the object of the class. It can access only class
variables.
Read More: Python Class Method vs. Static Method vs. Instance Method
class Student:
# class variable
# constructor
# instance variables
self.name = name
self.age = age
# instance method
def show(self):
# instance method
self.age = new_age
# class method
@classmethod
cls.school_name = new_name
s1 = Student("Harry", 12)
s1.show()
s1.change_age(14)
Student.modify_school_name('XYZ School')
s1.show()
Run
Output
Student: Harry 12 ABC School
We should follow specific rules while we are deciding a name for the class in Python.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 7/10
8/8/22, 8:14 PM Classes and Objects in Python
The pass statement is used to have an empty block in a code because the empty code is not allowed
in loops, function definition, class definition. Thus, the pass statement will results in no operation
(NOP). Generally, we use it as a placeholder when we do not know what code to write or add code
in a future release.
For example, suppose we have a class that is not implemented yet, but we want to implement it in
the future, and they cannot have an empty body because the interpreter gives an error. So use the
pass statement to construct a body that does nothing.
Example
class Demo:
pass
Run
In the above example, we defined class without a body. To avoid errors while executing it, we
added the pass statement in the class body.
Object Properties
Every object has properties with it. In other words, we can say that object property is an association
between name and value.
For example, a car is an object, and its properties are car color, sunroof, price, manufacture, model,
engine, and so on. Here, color is the name and red is the value. Object properties are nothing but
instance variables.
Object Properties
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 8/10
8/8/22, 8:14 PM Classes and Objects in Python
Every object has properties associated with them. We can set or modify the object’s properties after
object initialization by calling the property directly using the dot operator.
Obj.PROPERTY = value
Run
Example
class Fruit:
self.name = name
self.color = color
def show(self):
obj.name = "strawberry"
obj.show()
self.name = name
self.color = color
def show(self):
del obj.name
print(obj.name)
In the above example, As we can see, the attribute name has been deleted when we try to print or
access that attribute gets an error message.
Delete Objects
In Python, we can also delete the object by using a del keyword. An object can be anything like,
class object, list, tuple, set, etc.
Syntax
del object_name
Run
class Employee:
depatment = "IT"
def show(self):
emp = Employee()
emp.show()
# delete object
del emp
emp.show()
In the above example, we create the object emp of the class Employee. After that, using the del
keyword, we deleted that object.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-classes-and-objects%2F 10/10
8/8/22, 8:15 PM Constructors in Python
Constructors in Python
Constructor is a special method used to create and initialize an object of a class. On the other
hand, a destructor is used to destroy the object.
For example, when we execute obj = Sample(), Python gets to know that obj is an object of class
Sample and calls the constructor of that class to create an object.
Note: In Python, internally, the __new__ is the method that creates the object, and __del__ method is
called to destroy the object when the reference count for that object becomes zero.
In Python, Object creation is divided into two parts in Object Creation and Object initialization
Syntax of a constructor
def __init__(self):
Where,
Note: The __init__() method arguments are optional. We can define a constructor with any
number of arguments.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 1/9
8/8/22, 8:15 PM Constructors in Python
In this example, we’ll create a Class Student with an instance variable student name. we’ll see how
to use a constructor to initialize the student name at the time of object creation.
class Student:
# constructor
print('Inside Constructor')
self.name = name
# instance Method
def show(self):
s1 = Student('Emma')
s1.show()
Run
Output
Inside Constructor
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 2/9
8/8/22, 8:15 PM Constructors in Python
Note:
For every object, the constructor will be executed only once. For example, if we create
four objects, the constructor is called four times.
In Python, every class has a constructor, but it’s not required to define it explicitly.
Defining constructors in class is optional.
Python will provide a default constructor if no constructor is defined.
Types of Constructors
In Python, we have the following three types of constructors.
Default Constructor
Non-parametrized constructor
Parameterized constructor
Types of constructor
Default Constructor
Python will provide a default constructor if no constructor is defined. Python adds a default
constructor when we do not include the constructor in the class or forget to declare it. It does not
perform any task but initializes the objects. It is an empty constructor without a body.
If you do not implement any constructor in your class or forget to declare it, the Python inserts a
default constructor into your code on your behalf. This constructor is known as the default
constructor.
It does not perform any task but initializes the objects. It is an empty constructor without a body.
Note:
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 3/9
8/8/22, 8:15 PM Constructors in Python
The default constructor is not present in the source py file. It is inserted into the code
during compilation if not exists. See the below image.
If you implement your constructor, then the default constructor will not be added.
Example:
class Employee:
def display(self):
print('Inside Display')
emp = Employee()
emp.display()
Run
Output
Inside Display
As you can see in the example, we do not have a constructor, but we can still create an object for
the class because Python added the default constructor during a program compilation.
Non-Parametrized Constructor
A constructor without any arguments is called a non-parameterized constructor. This type of
constructor is used to initialize each object with default values.
This constructor doesn’t accept the arguments during object creation. Instead, it initializes every
object with the same set of values.
class Company:
# no-argument constructor
def __init__(self):
self.name = "PYnative"
def show(self):
cmp = Company()
cmp.show()
Run
Output
Name: PYnative Address: ABC Street
As you can see in the example, we do not send any argument to a constructor while creating an
object.
Parameterized Constructor
A constructor with defined parameters or arguments is called a parameterized constructor. We can
pass different values to each object at the time of creation using a parameterized constructor.
The first parameter to constructor is self that is a reference to the being constructed, and the rest of
the arguments are provided by the programmer. A parameterized constructor can have any number
of arguments.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 4/9
8/8/22, 8:15 PM Constructors in Python
For example, consider a company that contains thousands of employees. In this case, while creating
each employee object, we need to pass a different name, age, and salary. In such cases, use the
parameterized constructor.
Example:
class Employee:
# parameterized constructor
self.name = name
self.age = age
self.salary = salary
# display object
def show(self):
emma.show()
kelly.show()
Run
Output
Emma 23 7500
Kelly 25 8500
In the above example, we define a parameterized constructor which takes three parameters.
The following example shows how to use the default values with the constructor.
Example
class Student:
self.name = name
self.age = age
self.classroom = classroom
# display Student
def show(self):
emma = Student('Emma')
emma.show()
kelly.show()
Run
Output
Emma 12 7
Kelly 13 7
As you can see, we didn’t pass the age and classroom value at the time of object creation, so
default values are used.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 5/9
8/8/22, 8:15 PM Constructors in Python
Whenever we call an instance method through an object, the Python compiler implicitly passes
object reference as the first argument commonly known as self.
It is not mandatory to name the first parameter as a self. We can give any name whatever we like,
but it has to be the first parameter of an instance method.
Example
class Student:
# constructor
self.name = name
self.age = age
def show(self):
print(self.name, self.age)
emma.show()
kelly.show()
Run
Output
Emma 12
Kelly 13
Constructor Overloading
Constructor overloading is a concept of having more than one constructor with a different
parameters list in such a way so that each constructor can perform different tasks.
For example, we can create a three constructor which accepts a different set of parameters
Python does not support constructor overloading. If we define multiple constructors then, the
interpreter will considers only the last constructor and throws an error if the sequence of the
arguments doesn’t match as per the last constructor. The following example shows the same.
Example
class Student:
self.name = name
self.name = name
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 6/9
8/8/22, 8:15 PM Constructors in Python
self.age = age
emma = Student('Emma')
Run
Output
TypeError: __init__() missing 1 required positional argument: 'age'
As you can see in the above example, we defined multiple constructors with different
arguments.
At the time of object creation, the interpreter executed the second constructor because
Python always considers the last constructor.
Internally, the object of the class will always call the last constructor, even if the class
has multiple constructors.
In the example when we called a constructor only with one argument, we got a type
error.
Constructor Chaining
Constructors are used for instantiating an object. The task of the constructor is to assign value to
data members when an object of the class is created.
Constructor chaining is the process of calling one constructor from another constructor. Constructor
chaining is useful when you want to invoke multiple constructors, one after another, by initializing
only one instance.
In Python, constructor chaining is convenient when we are dealing with inheritance. When an
instance of a child class is initialized, the constructors of all the parent classes are first invoked and
then, in the end, the constructor of the child class is invoked.
Using the super() method we can invoke the parent class constructor from a child class.
Example
class Vehicle:
# Constructor of Vehicle
self.engine = engine
class Car(Vehicle):
# Constructor of Car
super().__init__(engine)
self.max_speed = max_speed
class Electric_Car(Car):
super().__init__(engine, max_speed)
self.km_range = km_range
Run
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 7/9
8/8/22, 8:15 PM Constructors in Python
Output
Inside Vehicle Constructor
Example
class Employee:
count = 0
def __init__(self):
Employee.count = Employee.count + 1
# creating objects
e1 = Employee()
e2 = Employee()
e2 = Employee()
Run
Output
The number of employee: 3
The __init__() is required to return None. We can not return something else. If we try to return a
non-None value from the __init__() method, it will raise TypeError.
Example
class Test:
self.id = i
return True
d = Test(10)
Run
Output
TypeError: __init__() should return None, not 'bool'
The below list contains the summary of the concepts we learned in this tutorial.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 8/9
8/8/22, 8:15 PM Constructors in Python
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-constructors%2F 9/9
8/8/22, 8:15 PM Python Destructors to Destroy the Object
Python has a garbage collector that handles memory management automatically. For example, it
cleans up the memory when an object goes out of scope.
But it’s not just memory that has to be freed when an object is destroyed. We must release or close
the other resources object were using, such as open files, database connections, cleaning up the
buffer or cache. To perform all those cleanup tasks we use destructor in Python.
The destructor is the reverse of the constructor. The constructor is used to initialize objects, while
the destructor is used to delete or destroy the object that releases the resource occupied by the
object.
In Python, destructor is not called manually but completely automatic. destructor gets called in
the following two cases
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-destructor%2F 1/7
8/8/22, 8:15 PM Python Destructors to Destroy the Object
This method is automatically called by Python when the instance is about to be destroyed. It is also
called a finalizer or (improperly) a destructor.
# body of a destructor
Run
Where,
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-destructor%2F 2/7
8/8/22, 8:15 PM Python Destructors to Destroy the Object
Note: The __del__() method arguments are optional. We can define a destructor with any number
of arguments.
Example
Let’s see how to create a destructor in Python with a simple example. In this example, we’ll create
a Class Student with a destructor. We’ll see: –
class Student:
# constructor
print('Inside Constructor')
self.name = name
print('Object initialized')
def show(self):
# destructor
def __del__(self):
print('Inside destructor')
print('Object destroyed')
# create object
s1 = Student('Emma')
s1.show()
# delete object
del s1
Run
Output
Inside Constructor
Object initialized
Inside destructor
Object destroyed
Note:
As you can see in the output, the __del__() method get called automatically is called when we
deleted the object reference using del s1.
In the above code, we created one object. The s1 is the reference variable that is pointing to the
newly created object.
The destructor has called when the reference to the object is deleted or the reference count for the
object becomes zero
The __del__ method is called for any object when the reference count for that object
becomes zero.
The reference count for that object becomes zero when the application ends, or we
delete all references manually using the del keyword.
The destructor will not invoke when we delete object reference. It will only invoke
when all references to the objects get deleted.
Working of destructor
Example:
import time
class Student:
# constructor
print('Inside Constructor')
self.name = name
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-destructor%2F 4/7
8/8/22, 8:15 PM Python Destructors to Destroy the Object
def show(self):
# destructor
def __del__(self):
print('Object destroyed')
# create object
s1 = Student('Emma')
# create new reference
s2 = s1
s1.show()
del s1
time.sleep(5)
print('After sleep')
s2.show()
Run
Output:
Inside Constructor
After Sleep
After sleep
Object destroyed
As you can see in the output destructors only invoked when all references to the objects
get deleted.
Also, the destructor is executed when the code (application) ends and the object is
available for the garbage collector. (I.e., we didn’t delete object reference s2 manually
using del s2).
Circular Referencing
The __del()__() doesn’t work correctly in the case of circular referencing. In circular referencing
occurs when two objects refer to each other.
When both objects go out of scope, Python doesn’t know which object to destroy first. So, to avoid
any errors, it doesn’t destroy any of them.
In short, it means that the garbage collector does not know the order in which the object should be
destroyed, so it doesn’t delete them from memory.
Ideally, the destructor must execute when an object goes out of scope, or its reference count reaches
zero.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-destructor%2F 5/7
8/8/22, 8:15 PM Python Destructors to Destroy the Object
But the objects involved in this circular reference will remain stored in the memory as long as the
application will run.
Example:
In the below example, ideally, both Vehicle and Car objects must be destroyed by the garbage
collector after they go out of scope. Still, because of the circular reference, they remain in memory.
I’d recommend using Python’s with statement for managing resources that need to be cleaned up.
import time
class Vehicle():
self.id = id;
self.dealer = car;
def __del__(self):
class Car():
self.id = id;
def __del__(self):
c = Car(12)
del c
time.sleep(8)
Run
Output:
Vehicle 12 created
Car 12 created
In OOP, if any exception occurs in the constructor while initializing the object, the constructor
destroys the object.
Likewise, in Python, if any exception occurs in the init method while initializing the object, the
method del gets called. But actually, an object is not created successfully, and resources are not
allocated to it
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-destructor%2F 6/7
8/8/22, 8:15 PM Python Destructors to Destroy the Object
even though the object was never initialized correctly, the del method will try to empty all the
resources and, in turn, may lead to another exception.
Example:
class Vehicle:
self.speed = speed;
def __del__(self):
print('Release resources')
# creating an object
car = Vehicle(350);
del car
Run
Output:
Traceback (most recent call last):
Release resources
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-destructor%2F 7/7
8/8/22, 8:16 PM Encapsulation in Python
Encapsulation in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP),
including abstraction, inheritance, and polymorphism. This lesson will cover what encapsulation is
and how to implement it in Python.
Encapsulation in Python
Need for Encapsulation
Data Hiding using public, protected, and private members
Data Hiding vs. Encapsulation
Getter and Setter Methods
Benefits of Encapsulation
Example:
In this example, we create an Employee class by defining employee attributes such as name and
salary as an instance variable and implementing behavior using work() and show() instance
methods.
class Employee:
# constructor
# data members
self.name = name
self.salary = salary
self.project = project
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-encapsulation%2F 1/7
8/8/22, 8:16 PM Encapsulation in Python
# method
def show(self):
# method
def work(self):
emp.show()
emp.work()
Run
Output:
Name: Jessa Salary: 8000
Using encapsulation, we can hide an object’s internal representation from the outside. This is called
information hiding.
Also, encapsulation allows us to restrict accessing variables and methods directly and prevent
accidental data modification by creating private data members and methods within a class.
Encapsulation is a way to can restrict access to methods and variables from outside of class.
Whenever we are working with the class and dealing with sensitive data, providing access to all
variables used within the class is not a good choice.
For example, Suppose you have an attribute that is not visible from the outside of an object and
bundle it with methods that provide read or write access. In that case, you can hide specific
information and control access to the object’s internal state. Encapsulation offers a way for us to
access the required variable without providing the program full-fledged access to all variables of a
class. This mechanism is used to protect the data of an object from other objects.
Access modifiers limit access to the variables and methods of a class. Python provides three types
of access modifiers private, public, and protected.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-encapsulation%2F 2/7
8/8/22, 8:16 PM Encapsulation in Python
Public Member
Public data members are accessible within and outside of a class. All member variables of the class
are by default public.
Example:
class Employee:
# constructor
self.name = name
self.salary = salary
def show(self):
emp.show()
Run
Output
Name: Jessa Salary: 10000
Private Member
We can protect variables in the class by marking them private. To define a private variable add two
underscores as a prefix at the start of a variable name.
Private members are accessible only within the class, and we can’t access them directly from the
class objects.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-encapsulation%2F 3/7
8/8/22, 8:16 PM Encapsulation in Python
Example:
class Employee:
# constructor
self.name = name
# private member
self.__salary = salary
print('Salary:', emp.__salary)
Run
Output
AttributeError: 'Employee' object has no attribute '__salary'
In the above example, the salary is a private variable. As you know, we can’t access the private
variable from the outside of that class.
We can access private members from outside of a class using the following two approaches
# constructor
self.name = name
# private member
self.__salary = salary
def show(self):
emp.show()
Run
Output:
Name: Jessa Salary: 10000
# constructor
self.name = name
# private member
self.__salary = salary
print('Name:', emp.name)
print('Salary:', emp._Employee__salary)
Run
Output
Name: Jessa
Salary: 10000
Protected Member
Protected members are accessible within the class and also available to its sub-classes. To define a
protected member, prefix the member name with a single underscore _.
Protected data members are used when you implement inheritance and want to allow data members
access to only child classes.
class Company:
def __init__(self):
# Protected member
self._project = "NLP"
# child class
class Employee(Company):
self.name = name
Company.__init__(self)
def show(self):
c = Employee("Jessa")
c.show()
print('Project:', c._project)
Run
Output
Employee name : Jessa
Project: NLP
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-encapsulation%2F 5/7
8/8/22, 8:16 PM Encapsulation in Python
To implement proper encapsulation in Python, we need to use setters and getters. The primary
purpose of using getters and setters in object-oriented programs is to ensure data encapsulation.
Use the getter method to access data members and the setter methods to modify the data members.
In Python, private variables are not hidden fields like in other programming languages. The getters
and setters methods are often used when:
Example
class Student:
# private member
self.name = name
self.__age = age
# getter method
def get_age(self):
return self.__age
# setter method
stud.set_age(16)
Output
Name: Jessa 14
Name: Jessa 16
Let’s take another example that shows how to use encapsulation to implement information hiding
and apply additional validation before changing the values of your object attributes (data member).
Example: Information Hiding and conditional logic for setting an object attributes
class Student:
# private member
self.name = name
self.__roll_no = roll_no
self.__age = age
def show(self):
# getter methods
def get_roll_no(self):
return self.__roll_no
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-encapsulation%2F 6/7
8/8/22, 8:16 PM Encapsulation in Python
else:
self.__roll_no = number
# before Modify
jessa.show()
jessa.set_roll_no(120)
jessa.set_roll_no(25)
jessa.show()
Run
Output:
Student Details: Jessa 10
Advantages of Encapsulation
Security: The main advantage of using encapsulation is the security of the data.
Encapsulation protects an object from unauthorized access. It allows private and
protected access levels to prevent accidental data modification.
Data Hiding: The user would not be knowing what is going on behind the scene. They
would only be knowing that to modify a data member, call the setter method. To read a
data member, call the getter method. What these setter and getter methods are doing is
hidden from them.
Simplicity: It simplifies the maintenance of the application by keeping classes separated
and preventing them from tightly coupling with each other.
Aesthetics: Bundling data and methods within a class makes code more readable and
maintainable
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-encapsulation%2F 7/7
8/8/22, 8:17 PM Polymorphism in Python
Polymorphism in Python
Object-Oriented Programming (OOP) has four essential characteristics: abstraction, encapsulation,
inheritance, and polymorphism.
This lesson will cover what polymorphism is and how to implement them in Python. Also, you’ll
learn how to implement polymorphism using function overloading, method overriding, and
operator overloading.
For example, Jessa acts as an employee when she is at the office. However, when she is at home,
she acts like a wife. Also, she represents herself differently in different places. Therefore, the same
person takes different forms as per the situation.
In polymorphism, a method can process objects differently depending on the class type or data
type. Let’s see simple examples to understand it better.
Example:
students = ['Emma', 'Jessa', 'Kelly']
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 1/10
8/8/22, 8:17 PM Polymorphism in Python
# calculate count
print(len(students))
print(len(school))
Run
Output
3
10
Using method overriding polymorphism allows us to defines methods in the child class that have
the same name as the methods in the parent class. This process of re-implementing the inherited
method in the child class is known as Method Overriding.
It is effective when we want to extend the functionality by altering the inherited method.
Or the method inherited from the parent class doesn’t fulfill the need of a child class, so
we need to re-implement the same method in the child class in a different way.
Method overriding is useful when a parent class has multiple child classes, and one of
that child class wants to redefine the method. The other child classes can use the parent
class method. Due to this, we don’t need to modification the parent class code
In polymorphism, Python first checks the object’s class type and executes the appropriate
method when we call the method. For example, If you create the Car object, then Python calls the
speed() method from a Car class.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 2/10
8/8/22, 8:17 PM Polymorphism in Python
class Vehicle:
self.name = name
self.color = color
self.price = price
def show(self):
def max_speed(self):
def change_gear(self):
class Car(Vehicle):
def max_speed(self):
def change_gear(self):
# Car Object
car.show()
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 3/10
8/8/22, 8:17 PM Polymorphism in Python
car.max_speed()
car.change_gear()
# Vehicle Object
vehicle.show()
vehicle.max_speed()
vehicle.change_gear()
Run
Output:
Details: Car x1 Red 20000
As you can see, due to polymorphism, the Python interpreter recognizes that the max_speed() and
change_gear() methods are overridden for the car object. So, it uses the one defined in the child
class (Car)
On the other hand, the show() method isn’t overridden in the Car class, so it is used from the
Vehicle class.
Example
self.basket = list(basket)
self.buyer = buyer
def __len__(self):
print('Redefine length')
count = len(self.basket)
return count * 2
print(len(shopping))
Run
Output
Redefine length
method. Thus, we can call the methods without being concerned about which class type each object
is. We assume that these methods exist in each class.
Python allows different classes to have methods with the same name.
Let’s design a different class in the same way by adding the same methods in two or
more classes.
Next, create an object of each class
Next, add all objects in a tuple.
In the end, iterate the tuple using a for loop and call methods of a object without
checking its class.
Example
In the below example, fuel_type() and max_speed() are the instance methods created in both
classes.
class Ferrari:
def fuel_type(self):
print("Petrol")
def max_speed(self):
class BMW:
def fuel_type(self):
print("Diesel")
def max_speed(self):
ferrari = Ferrari()
bmw = BMW()
car.fuel_type()
car.max_speed()
Run
Output
Petrol
Diesel
As you can see, we have created two classes Ferrari and BMW. They have the same instance
method names fuel_type() and max_speed(). However, we have not linked both the classes nor
have we used inheritance.
We packed two different objects into a tuple and iterate through it using a car variable. It is possible
due to polymorphism because we have added the same method in both classes Python first checks
the object’s class type and executes the method present in its class.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 5/10
8/8/22, 8:17 PM Polymorphism in Python
Example
class Ferrari:
def fuel_type(self):
print("Petrol")
def max_speed(self):
class BMW:
def fuel_type(self):
print("Diesel")
def max_speed(self):
# normal function
def car_details(obj):
obj.fuel_type()
obj.max_speed()
ferrari = Ferrari()
bmw = BMW()
car_details(ferrari)
car_details(bmw)
Run
Output
Petrol
The built-in function reversed(obj) returns the iterable by reversing the given object. For example,
if you pass a string to it, it will reverse it. But if you pass a list of strings to it, it will return the
iterable by reversing the order of elements (it will not reverse the individual string).
Let us see how a built-in method process objects having different data types.
Example:
students = ['Emma', 'Jessa', 'Kelly']
print('Reverse string')
for i in reversed('PYnative'):
print('\nReverse list')
Output:
Reverse string
e v i t a n Y P
Reverse list
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 6/10
8/8/22, 8:17 PM Polymorphism in Python
Method Overloading
The process of calling the same method with different parameters is known as method overloading.
Python does not support method overloading. Python considers only the latest defined method even
if you overload the method. Python will raise a TypeError if you overload the method.
Example
def addition(a, b):
c = a + b
print(c)
d = a + b + c
print(d)
# addition(4, 5)
addition(3, 7, 5)
Run
To overcome the above problem, we can use different ways to achieve the method overloading. In
Python, to overload the class method, we need to write the method’s logic so that different code
executes inside the function depending on the parameter passes.
For example, the built-in function range() takes three parameters and produce different result
depending upon the number of parameters passed to it.
Example:
for i in range(5): print(i, end=', ')
print()
print()
Output:
0, 1, 2, 3, 4,
5, 6, 7, 8, 9,
2, 4, 6, 8, 10,
Let’s assume we have an area() method to calculate the area of a square and rectangle. The method
will calculate the area depending upon the number of parameters passed to it.
if b > 0:
else:
square = Shape()
square.area(5)
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 7/10
8/8/22, 8:17 PM Polymorphism in Python
rectangle = Shape()
rectangle.area(5, 3)
Run
Output:
Area of Square is: 25
For example, the + operator will perform an arithmetic addition operation when used with
numbers. Likewise, it will perform concatenation when used with strings.
The operator + is used to carry out different operations for distinct data types. This is one of the
most simple occurrences of polymorphism in Python.
Example:
# add 2 numbers
print(100 + 200)
print('Jess' + 'Roy')
Output:
300
JessRoy
Example:
class Book:
self.pages = pages
b1 = Book(400)
b2 = Book(300)
print(b1 + b2)
Run
Output
TypeError: unsupported operand type(s) for +: 'Book' and 'Book'
We can overload + operator to work with custom objects also. Python provides some special or
magic function that is automatically invoked when associated with that particular operator.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 8/10
8/8/22, 8:17 PM Polymorphism in Python
For example, when we use the + operator, the magic method __add__() is automatically invoked.
Internally + operator is implemented by using __add__() method. We have to override this method
in our class if you want to add two custom objects.
Example:
class Book:
self.pages = pages
b1 = Book(400)
b2 = Book(300)
Run
Output
Total number of pages: 700
Example:
class Employee:
self.name = name
self.salary = salary
# calculate salary
class TimeSheet:
self.name = name
self.days = days
Run
Output
Wroked for 50 days
Magic Methods
In Python, there are different magic methods available to perform overloading operations. The
below table shows the magic methods names to overload the mathematical operator, assignment
operator, and relational operators in Python.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 9/10
8/8/22, 8:17 PM Polymorphism in Python
magic methods
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-polymorphism%2F 10/10
8/8/22, 8:18 PM Inheritance in Python
Inheritance in Python
The process of inheriting the properties of the parent class into a child class is called
inheritance. The existing class is called a base class or parent class and the new class is called a
subclass or child class or derived class.
In this Python lesson, you will learn inheritance, method overloading, method overriding, types of
inheritance, and MRO (Method Resolution Order).
In inheritance, the child class acquires all the data members, properties, and functions from the
parent class. Also, a child class can also provide its specific implementation to the methods of the
parent class.
For example, In the real world, Car is a sub-class of a Vehicle class. We can create a Car by
inheriting the properties of a Vehicle such as Wheels, Colors, Fuel tank, engine, and add extra
properties in Car as required.
Syntax
class BaseClass:
class DerivedClass(BaseClass):
Also, See
Types Of Inheritance
In Python, based upon the number of child and parent classes involved, there are five types of
inheritance. The type of inheritance are listed below:
1. Single inheritance
2. Multiple Inheritance
3. Multilevel inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single Inheritance
In single inheritance, a child class inherits from a single-parent class. Here is one child class and
one parent class.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 1/9
8/8/22, 8:18 PM Inheritance in Python
Example
Let’s create one parent class called ClassOne and one child class called ClassTwo to implement
single inheritance.
# Base class
class Vehicle:
def Vehicle_info(self):
# Child class
class Car(Vehicle):
def car_info(self):
car = Car()
car.Vehicle_info()
car.car_info()
Run
Output
Inside Vehicle class
Multiple Inheritance
In multiple inheritance, one child class can inherit from multiple parent classes. So here is one
child class and multiple parent classes.
Example
# Parent class 1
class Person:
# Parent class 2
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 2/9
8/8/22, 8:18 PM Inheritance in Python
class Company:
# Child class
class Employee(Person, Company):
emp = Employee()
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta')
Run
Output
Inside Person class
In the above example, we created two parent classes Person and Company respectively. Then we
create one child called Employee which inherit from Person and Company classes.
Multilevel inheritance
In multilevel inheritance, a class inherits from a child class or derived class. Suppose three classes
A, B, C. A is the superclass, B is the child class of A, C is the child class of B. In other words, we
can say a chain of classes is called multilevel inheritance.
Example
# Base class
class Vehicle:
def Vehicle_info(self):
# Child class
class Car(Vehicle):
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 3/9
8/8/22, 8:18 PM Inheritance in Python
def car_info(self):
# Child class
class SportsCar(Car):
def sports_car_info(self):
s_car = SportsCar()
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Run
Output
Inside Vehicle class
In the above example, we can see there are three classes named Vehicle, Car, SportsCar. Vehicle is
the superclass, Car is a child of Vehicle, SportsCar is a child of Car. So we can see the chaining of
classes.
Hierarchical Inheritance
In Hierarchical inheritance, more than one child class is derived from a single parent class. In other
words, we can say one parent class and multiple child classes.
Example
Let’s create ‘Vehicle’ as a parent class and two child class ‘Car’ and ‘Truck’ as a parent class.
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
class Truck(Vehicle):
obj1 = Car()
obj1.info()
obj1.car_info('BMW')
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 4/9
8/8/22, 8:18 PM Inheritance in Python
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
Run
Output
This is Vehicle
This is Vehicle
Hybrid Inheritance
When inheritance is consists of multiple types or a combination of different inheritance is called
hybrid inheritance.
Example
class Vehicle:
def vehicle_info(self):
class Car(Vehicle):
def car_info(self):
class Truck(Vehicle):
def truck_info(self):
def sports_car_info(self):
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Run
Note: In the above example, hierarchical and multiple inheritance exists. Here we created, parent
class Vehicle and two child classes named Car and Truck this is hierarchical inheritance.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 5/9
8/8/22, 8:18 PM Inheritance in Python
Another is SportsCar inherit from two parent classes named Car and Vehicle. This is multiple
inheritance.
In child class, we can refer to parent class by using the super() function. The super function returns
a temporary object of the parent class that allows us to call a parent class method inside a child
class method.
1. We are not required to remember or specify the parent class name to access its
methods.
2. We can use the super() function in both single and multiple inheritances.
3. The super() function support code reusability as there is no need to write the entire
function
Example
class Company:
def company_name(self):
return 'Google'
class Employee(Company):
def info(self):
c_name = super().company_name()
emp = Employee()
emp.info()
Run
Output:
Jessa works at Google
In the above example, we create a parent class Company and child class Employee. In Employee class,
we call the parent class method by using a super() function.
issubclass()
In Python, we can verify whether a particular class is a subclass of another class. For this purpose,
we can use Python built-in function issubclass(). This function returns True if the given class is
the subclass of the specified class. Otherwise, it returns False.
Syntax
issubclass(class, classinfo)
Run
Where,
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 6/9
8/8/22, 8:18 PM Inheritance in Python
Example
class Company:
def fun1(self):
class Employee(Company):
def fun2(self):
class Player:
def fun3(self):
# Result True
print(issubclass(Employee, Company))
# Result False
print(issubclass(Employee, list))
# Result False
print(issubclass(Player, Company))
# Result True
print(issubclass(Employee, (list, Company)))
# Result True
print(issubclass(Company, (list, Company)))
Run
Method Overriding
In inheritance, all members available in the parent class are by default available in the child class.
If the child class does not satisfy with parent class implementation, then the child class is allowed
to redefine that method by extending additional functions in the child class. This concept is called
method overriding.
When a child class method has the same name, same parameters, and same return type as a method
in its superclass, then the method in the child is said to override the method in the parent class.
Example
class Vehicle:
def max_speed(self):
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 7/9
8/8/22, 8:18 PM Inheritance in Python
class Car(Vehicle):
def max_speed(self):
car = Car()
car.max_speed()
Run
Output:
max speed is 200 Km/Hour
In the above example, we create two classes named Vehicle (Parent class) and Car (Child class).
The class Car extends from the class Vehicle so, all properties of the parent class are available in
the child class. In addition to that, the child class redefined the method max_speed().
This order is also called the Linearization of a class, and a set of rules is called MRO (Method
Resolution Order). The MRO plays an essential role in multiple inheritances as a single
method may found in multiple parent classes.
1. First, it searches in the current parent class if not available, then searches in the parents
class specified while inheriting (that is left to right.)
2. We can get the MRO of a class. For this purpose, we can use either the mro attribute or
the mro() method.
Example
class A:
def process(self):
class B(A):
def process(self):
def process(self):
C1 = C()
C1.process()
print(C.mro())
# In class C
In the above example, we create three classes named A, B and C. Class B is inherited from A, class C
inherits from B and A. When we create an object of the C class and calling the process() method,
Python looks for the process() method in the current class in the C class itself.
Then search for parent classes, namely B and A, because C class inherit from B and A. that is, C(B, A)
and always search in left to right manner.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 8/9
8/8/22, 8:18 PM Inheritance in Python
Next Steps
Python OOP Exercise
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-inheritance%2F 9/9
8/8/22, 8:19 PM Python Instance Variables Explained With Examples
In Object-oriented programming, when we design a class, we use instance variables and class
variables.
Instance variables: If the value of a variable varies from object to object, then such
variables are called instance variables.
Class Variables: A class variable is a variable that is declared inside of class, but
outside of any instance method or __init__() method.
Instance variables are not shared by objects. Every object has its own copy of the instance attribute.
This means that for each object of a class, the instance variable value is different.
When we create classes in Python, instance methods are used regularly. we need to create an object
to execute the block of code or action defined in the instance method.
Instance variables are used within the instance method. We use the instance method to perform a
set of actions on the data/value provided by the instance variable.
We can access the instance variable using the object and dot (.) operator.
In Python, to work with an instance variable and method, we use the self keyword. We use
the self keyword as the first parameter to a method. The self refers to the current object.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-variables%2F 1/8
8/8/22, 8:19 PM Python Instance Variables Explained With Examples
Example:
In the following example, we are creating two instance variable name and age in the Student class.
class Student:
# constructor
# Instance variable
self.name = name
self.age = age
s1 = Student("Jessa", 20)
print('Object 1')
print('Name:', s1.name)
print('Age:', s1.age)
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-variables%2F 2/8
8/8/22, 8:19 PM Python Instance Variables Explained With Examples
print('Object 2')
print('Name:', s2.name)
print('Age:', s2.age)
Run
Output
Object 1
Name: Jessa
Age: 20
Object 2
Name: Kelly
Age: 10
Note:
When we created an object, we passed the values to the instance variables using a
constructor.
Each object contains different values because we passed different values to a
constructor to initialize the object.
Variable declared outside __init__() belong to the class. They’re shared by all
instances.
Note: When you change the instance variable’s values of one object, the changes will not be
reflected in the remaining objects because every object maintains a separate copy of the instance
variable.
Example
class Student:
# constructor
# Instance variable
self.name = name
self.age = age
# create object
print('Before')
stud.name = 'Emma'
stud.age = 15
print('After')
Output
Before
After
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-variables%2F 3/8
8/8/22, 8:19 PM Python Instance Variables Explained With Examples
Within the class in instance method by using the object reference (self)
Using getattr() method
# constructor
# Instance variable
self.name = name
self.age = age
def show(self):
# create object
stud.show()
Run
Output
Name: Jessa Age: 20
Pass the object reference and instance variable name to the getattr() method to get the value of an
instance variable.
class Student:
# constructor
# Instance variable
self.name = name
self.age = age
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-variables%2F 4/8
8/8/22, 8:19 PM Python Instance Variables Explained With Examples
# create object
Output
Name: Jessa
Age: 20
Example:
class Student:
# Instance variable
self.name = name
self.age = age
# create object
print('Before')
stud.marks = 75
print('After')
Run
Output
Before
After
Note:
We cannot add an instance variable to a class from outside because instance variables
belong to objects.
Adding an instance variable to one object will not be reflected the remaining
objects because every object has a separate copy of the instance variable.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-variables%2F 5/8
8/8/22, 8:19 PM Python Instance Variables Explained With Examples
del statement: The del keyword is used to delete objects. In Python, everything is an
object, so the del keyword can also be used to delete variables, lists, or parts of a list,
etc.
delattr() function: Used to delete an instance variable dynamically.
Note: When we try to access the deleted attribute, it raises an attribute error.
# Instance variable
self.roll_no = roll_no
self.name = name
# create object
s1 = Student(10, 'Jessa')
print(s1.roll_no, s1.name)
# del name
del s1.name
print(s1.name)
Run
Output
10 Jessa
delattr() function
The delattr() function is used to delete the named attribute from the object with the prior
permission of the object. Use the following syntax.
delattr(object, name)
Example
class Student:
# Instance variable
self.roll_no = roll_no
self.name = name
def show(self):
print(self.roll_no, self.name)
s1 = Student(10, 'Jessa')
s1.show()
delattr(s1, 'roll_no')
s1.show()
Run
Output
10 Jessa
In this example, the engine is an instance variable of the Vehicle class. We inherited a Vehicle
class to access its instance variables in Car class
class Vehicle:
def __init__(self):
self.engine = '1500cc'
class Car(Vehicle):
super().__init__()
self.max_speed = max_speed
def display(self):
print("Engine:", self.engine)
# Object of car
car = Car(240)
car.display()
Run
Output
Engine: 1500cc
The __dict__ function returns a dictionary that contains variable name as a key and variable value
as a value
Example:
class Student:
# Instance variable
self.roll_no = roll_no
self.name = name
s1 = Student(10, 'Jessa')
print(s1.__dict__)
Run
Output:
Instance variable object has
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-variables%2F 7/8
8/8/22, 8:19 PM Python Instance Variables Explained With Examples
roll_no = 10
name = Jessa
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-variables%2F 8/8
8/8/22, 8:19 PM Python Instance Methods Explained With Examples
Instance methods: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods. It must have a
self parameter to refer to the current object.
Class methods: Used to access or modify the class state. In method implementation, if
we use only class variables, then such type of methods we should declare as a class
method. The class method has a cls parameter which refers to the class.
When we create a class in Python, instance methods are used regularly. To work with an instance
method, we use the self keyword. We use the self keyword as the first parameter to a method. The
self refers to the current object.
Any method we create in a class will automatically be created as an instance method unless we
explicitly tell Python that it is a class or static method.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-methods%2F 1/6
8/8/22, 8:19 PM Python Instance Methods Explained With Examples
Instance methods are defined inside a class, and it is pretty similar to defining a regular function.
You may use a variable named differently for self, but it is discouraged since self is the
recommended convention in Python.
Let’s see the example to create an instance method show() in the Student class to display the student
details.
Example:
class Student:
# constructor
# Instance variable
self.name = name
self.age = age
def show(self):
First, create instance variables name and age in the Student class.
Next, create an instance method display() to print student name and age.
Next, create object of a Student class to call the instance method.
et’s see how to call an instance method show() to access the student object details such as name and
age.
class Student:
# constructor
# Instance variable
self.name = name
self.age = age
def show(self):
print('First Student')
emma.show()
print('Second Student')
kelly.show()
Run
Output:
First Student
Name: Jessa Age: 14
Second Student
Note:
Inside any instance method, we can use self to access any data or method that reside in our class.
We are unable to access it without a self parameter.
An instance method can freely access attributes and even modify the value of attributes of an object
by using the self parameter.
By Using self.__class__ attribute we can access the class attributes and change the class state.
Therefore instance method gives us control of changing the object as well as the class state.
# Instance variable
self.roll_no = roll_no
self.name = name
self.age = age
def show(self):
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-methods%2F 3/6
8/8/22, 8:19 PM Python Instance Methods Explained With Examples
# instance method to modify instance variable
self.roll_no = roll_number
self.age = age
# create object
print('class VIII')
stud.show()
print('class IX')
stud.update(35, 15)
stud.show()
Run
Output:
class VIII
class IX
Example:
class Student:
# Instance variable
self.roll_no = roll_no
self.name = name
self.age = age
self.marks = marks
# create object
stud.add_marks(75)
# display object
Output:
Roll Number: 20 Name: Emma Age: 14 Marks: 75
When class is in a different file, and you don’t have access to modify the class structure
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-methods%2F 4/6
8/8/22, 8:19 PM Python Instance Methods Explained With Examples
You wanted to extend the class functionality without changing its basic structure
because many systems use the same structure.
Let’s see how to add an instance method in the Student class at runtime.
Example:
We should add a method to the object, so other instances don’t have access to that method. We use
the types module’s MethodType() to add a method to an object. Below is the simplest way to method
to an object.
import types
class Student:
# constructor
self.name = name
self.age = age
# instance method
def show(self):
def welcome(self):
# create object
s1 = Student("Jessa", 15)
s1.show()
s1.welcome()
Run
Output:
Name: Jessa Age: 15
By using the del operator
By using delattr() method
By using the del operator
Example:
In this example, we will delete an instance method named percentage() from a Student class. If
you try to access it after removing it, you’ll get an Attribute Error.
class Student:
# constructor
self.name = name
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-methods%2F 5/6
8/8/22, 8:19 PM Python Instance Methods Explained With Examples
self.age = age
# instance method
def show(self):
# instance method
emma.show()
emma.percentage(67, 62)
del emma.percentage
emma.percentage(67, 62)
Run
Output:
Name: Emma Age: 14
Percentage: 64.5
del emma.percentage
AttributeError: percentage
By using the delattr() method
The delattr() is used to delete the named attribute from the object with the prior permission of the
object. Use the following syntax to delete the instance method.
delattr(object, name)
Run
Example:
In this example, we will delete an instance method named percentage() from a Student class.
emma = Student('Emma', 14)
emma.show()
emma.percentage(67, 62)
delattr(emma, 'percentage')
emma.show()
emma.percentage(67, 62)
Run
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-instance-methods%2F 6/6
8/8/22, 8:20 PM Python Class Variables
Instance variables: If the value of a variable varies from object to object, then such
variables are called instance variables.
Class Variables: A class variable is a variable that is declared inside of class, but
outside of any instance method or __init__() method.
Class variables are shared by all instances of a class. Unlike instance variable, the value of a class
variable is not varied from object to object,
In Python, Class variables are declared when a class is being constructed. They are not defined
inside any methods of a class because of this only one copy of the static variable will be created
and shared between all objects of the class.
For example, in Student class, we can have different instance variables such as name and roll
number because each student’s name and roll number are different.
But, if we want to include the school name in the student class, we must use the class variable
instead of an instance variable as the school name is the same for all students. So instead of
maintaining the separate copy in each object, we can create a class variable that will hold the
school name so all students (objects) can share it.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 1/8
8/8/22, 8:20 PM Python Class Variables
By convention, typically it is placed right below the class header and before the constructor method
and other methods.
Example:
class Student:
# Class variable
self.name = name
self.roll_no = roll_no
s1 = Student('Emma', 10)
s2 = Student('Jessa', 20)
Run
Output
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 2/8
8/8/22, 8:20 PM Python Class Variables
In the above example, we created the class variable school_name and accessed it using the object
and class name.
Note: Like regular variables, class variables can store data of any type. We can use Python list,
Python tuple, and Python dictionary as a class variable.
Access inside the constructor by using either self parameter or class name.
Access class variable inside instance method by using either self of class name
Access from outside of class by using either object reference or class name.
# Class variable
# constructor
self.name = name
print(self.school_name)
print(Student.school_name)
# create Object
s1 = Student('Emma')
Run
Output
ABC School
ABC School
# Class variable
# constructor
self.name = name
self.roll_no = roll_no
# Instance method
def show(self):
print(Student.school_name)
# create Object
s1 = Student('Emma', 10)
s1.show()
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 3/8
8/8/22, 8:20 PM Python Class Variables
print('Outside class')
print(s1.school_name)
print(Student.school_name)
Run
Output
Inside instance method
ABC School
Outside class
ABC School
ABC School
In this example, we accessed the class variable school_name using class name and a self keyword
inside a method.
Note: We should change the class variable’s value using the class name only.
Example
class Student:
# Class variable
# constructor
self.name = name
self.roll_no = roll_no
# Instance method
def show(self):
# create Object
s1 = Student('Emma', 10)
print('Before')
s1.show()
print('After')
s1.show()
Run
Output:
Before
After
Note:
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 4/8
8/8/22, 8:20 PM Python Class Variables
It is best practice to use a class name to change the value of a class variable. Because if we try to
change the class variable’s value by using an object, a new instance variable is created for that
particular object, which shadows the class variables.
Example:
class Student:
# Class variable
# constructor
self.name = name
self.roll_no = roll_no
# create Objects
s1 = Student('Emma', 10)
s2 = Student('Jessa', 20)
print('Before')
print('After')
Run
Output:
Before
After
A new instance variable is created for the s1 object, and this variable shadows the class variables.
So always use the class name to modify the class variable.
Instance variables: Instance variable’s value varies from object to object. Instance
variables are not shared by objects. Every object has its own copy of the instance
attribute
Class Variables: A class variable is a variable that is declared inside of class, but
outside of any instance method or __init__() method. Class variables are shared by all
instances of a class.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 5/8
8/8/22, 8:20 PM Python Class Variables
Instance variables are not shared by Class variables are shared by all instances.
Instance variables are declared inside the Class variables are declared inside the class
constructor i.e., the __init__() method. definition but outside any of the instance
methods and constructors.
It is gets created when an instance of the It is created when the program begins to execute.
class is created.
Changes made to these variables through Changes made in the class variable will reflect in
one object will not reflect in another all objects.
object.
Example:
Let’s see the example to create a class variable and instance variable.
class Car:
# Class variable
manufacturer = 'BMW'
# instance variable
self.model = model
self.price = price
# create Object
Output:
x1 2500 BMW
When we use inheritance, all variables and methods of the base class are available to the child
class. In such cases, We can also change the value of the parent class’s class variable in the child
class.
We can use the parent class or child class name to change the value of a parent class’s class
variable in the child class.
Example
class Course:
# class variable
course = "Python"
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 6/8
8/8/22, 8:20 PM Python Class Variables
class Student(Course):
self.name = name
def show_student(self):
print('Before')
print('Now')
stud = Student("Emma")
stud.show_student()
Run
Output
Before
Now
What if both child class and parent class has the same class variable name. In this case, the
child class will not inherit the class variable of a base class. So it is recommended to create a
separate class variable for child class instead of inheriting the base class variable.
Example:
class Course:
# class variable
course = "Python"
class Student(Course):
# class variable
course = "SQL"
self.name = name
def show_student(self):
print('Before')
print('Now')
stud = Student("Emma")
stud.show_student()
Output:
Before
Now
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 7/8
8/8/22, 8:20 PM Python Class Variables
For example,
Example
class Player:
# class variables
club = 'Chelsea'
sport = 'Football'
# Instance variable
self.name = name
def show(self):
p1 = Player('John')
p1.club = 'FC'
p1.show()
p2 = Player('Emma')
p2.sport = 'Tennis'
p2.show()
Output
Player : Name: John Club: FC Sports: Football
In the above example, the instance variable name is unique for each player. The class variable team
and sport can be accessed and modified by any object.
Because both objects modified the class variable, a new instance variable is created for that
particular object with the same name as the class variable, which shadows the class variables.
In our case, for object p1 new instance variable club gets created, and for object p2 new instance
variable sport gets created.
So when you try to access the class variable using the p1 or p2 object, it will not return the actual
class variable value.
To avoid this, always modify the class variable value using the class name so that all objects gets
the updated value. Like this
Player.club = 'FC'
Player.sport = 'Tennis'
Run
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-variables%2F 8/8
8/8/22, 8:23 PM Python Class Method Explained With Examples
Instance method: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods. It must have a
self parameter to refer to the current object.
Class method: Used to access or modify the class state. In method implementation, if
we use only class variables, then such type of methods we should declare as a class
method. The class method has a cls parameter which refers to the class.
Static method: It is a general utility method that performs a task in isolation. Inside this
method, we don’t use instance or class variable because this static method doesn’t take
any parameters like self and cls.
A class method is bound to the class and not the object of the class. It can access only
class variables.
It can modify the class state by changing the value of a class variable that would apply
across all the class objects.
In method implementation, if we use only class variables, we should declare such methods as class
methods. The class method has a cls as the first parameter, which refers to the class.
Class methods are used when we are dealing with factory methods. Factory methods are those
methods that return a class object for different use cases. Thus, factory methods create concrete
implementations of a common interface.
The class method can be called using ClassName.method_name() as well as by using an object of the
class.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method%2F 1/7
8/8/22, 8:23 PM Python Class Method Explained With Examples
Class methods are defined inside a class, and it is pretty similar to defining a regular function.
Like, inside an instance method, we use the self keyword to access or modify the instance
variables. Same inside the class method, we use the cls keyword as a first parameter to access class
variables. Therefore the class method gives us control of changing the class state.
You may use a variable named differently for cls, but it is discouraged since self is the
recommended convention in Python.
The class method can only access the class attributes, not the instance attributes
The @classmethod decorator is a built-in function decorator. In Python, we use the @classmethod
decorator to declare a method as a class method. The @classmethod decorator is an expression that
gets evaluated after our function is defined.
Let’s see how to create a factory method using the class method. In this example, we will create a
Student class object using the class method.
from datetime import date
class Student:
self.name = name
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method%2F 2/7
8/8/22, 8:23 PM Python Class Method Explained With Examples
self.age = age
@classmethod
def show(self):
jessa.show()
joy.show()
Run
Output
Jessa's age is: 20
In the above example, we created two objects, one using the constructor and the second
using the calculate_age() method.
The constructor takes two arguments name and age. On the other hand, class method
takes cls, name, and birth_year and returns a class instance which nothing but a new
object.
The @classmethod decorator is used for converting calculate_age() method to a class
method.
The calculate_age() method takes Student class (cls) as a first parameter and returns
constructor by calling Student(name, date.today().year - birthYear), which is
equivalent to Student(name, age).
Syntax:
classmethod(function)
Run
function: It is the name of the method you want to convert as a class method.
It returns the converted class method.
Note: The method you want to convert as a class method must accept class (cls) as the first
argument, just like an instance method receives the instance (self).
As we know, the class method is bound to class rather than an object. So we can call the class
method both by calling class and object.
A classmethod() function is the older way to create the class method in Python. In a newer version
of Python, we should use the @classmethod decorator to create a class method.
# class variable
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method%2F 3/7
8/8/22, 8:23 PM Python Class Method Explained With Examples
def school_name(cls):
School.school_name = classmethod(School.school_name)
School.school_name()
Run
Output
School Name is : ABC School
Class variables are shared by all instances of a class. Using the class method we can modify the
class state by changing the value of a class variable that would apply across all the class objects.
class Student:
self.name = name
self.age = age
@classmethod
# class_name.class_variable
cls.school_name = school_name
# instance method
def show(self):
jessa.show()
# change school_name
Student.change_school('XYZ School')
jessa.show()
Run
Output:
Jessa 20 School: ABC School
Let’s create a Vehicle class that contains a factory class method from_price() that will return a
Vehicle instance from a price. When we call the same method using the child’s class name, it will
return the child’s class object.
Whenever we derive a class from a parent class that has a class method then it creates the correct
instance of the derived class. The following example shows how the class method works in
inheritance.
Example
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method%2F 4/7
8/8/22, 8:23 PM Python Class Method Explained With Examples
class Vehicle:
brand_name = 'BMW'
self.name = name
self.price = price
@classmethod
# ind_price = dollar * 76
def show(self):
print(self.name, self.price)
class Car(Vehicle):
bmw_us.show()
bmw_ind.show()
# check type
print(type(bmw_ind))
Run
Output
BMW X5 65000
BMW X5 4875000
class '__main__.Car'
We need to use the classmethod() function to add a new class method to a class.
Example:
Let’s see how to add a new class method in the Student class at runtime.
class Student:
self.name = name
self.age = age
def show(self):
print(self.name, self.age)
# class ended
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method%2F 5/7
8/8/22, 8:23 PM Python Class Method Explained With Examples
def exercises(cls):
Student.exercises = classmethod(exercises)
jessa.show()
Student.exercises()
Run
Output
Jessa 14
By using the del operator
By using delattr() method
By using the del operator
The del operator removes the instance method added by class. Use the del
class_name.class_method syntax to delete the class method.
Example:
In this example, we will delete the class method named change_school() from a Student class. If
you try to access it after removing it, you’ll get an Attribute Error.
class Student:
self.name = name
self.age = age
@classmethod
cls.school_name = school_name
print(Student.change_school('XYZ School'))
print(Student.school_name)
del Student.change_school
print(Student.change_school('PQR School'))
Run
Output
XYZ School
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method%2F 6/7
8/8/22, 8:23 PM Python Class Method Explained With Examples
The delattr() method is used to delete the named attribute and method from the class. The
argument to delattr is an object and string. The string must be the name of an attribute or method
name.
Example
jessa = Student('Jessa', 20)
print(Student.change_school('XYZ School'))
print(Student.school_name)
delattr(Student, 'change_school')
print(Student.change_school('PQR School'))
Run
Output
XYZ School
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method%2F 7/7
8/8/22, 8:24 PM Python Static Method Explained With Examples
Class methods: Used to access or modify the state of the class. if we use only class
variables, we should declare such methods as a class method.
Static methods: A static method is a general utility method that performs a task in
isolation. Inside this method, we don’t use instance or class variable because this static
method doesn’t take any parameters like self and cls.
A static method is bound to the class and not the object of the class. Therefore, we can call it using
the class name.
A static method doesn’t have access to the class and instance variables because it does not receive
an implicit first argument like self and cls. Therefore it cannot modify the state of the object or
class.
The class method can be called using ClassName.method_name() as well as by using an object of the
class.
class Employee:
@staticmethod
def sample(x):
Employee.sample(10)
emp = Employee()
emp.sample(10)
Run
Static methods are defined inside a class, and it is pretty similar to defining a regular function. To
declare a static method, use this idiom:
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-static-method%2F 1/4
8/8/22, 8:24 PM Python Static Method Explained With Examples
class C:
@staticmethod
In this example, we will create a static method gather_requirement() that accepts the project name
and returns all requirements to complete under this project.
Static methods are a special case of methods. Sometimes, you’ll write code that belongs to a class,
but that doesn’t use the object itself at all. It is a utility method and doesn’t need an object (self
parameter) to complete its operation. So we declare it as a static method. Also, we can call it from
another method of a class.
class Employee(object):
self.name = name
self.salary = salary
self.project_name = project_name
@staticmethod
def gather_requirement(project_name):
else:
requirement = ['task_1']
return requirement
# instance method
def work(self):
requirement = self.gather_requirement(self.project_name)
print('Completed', task)
emp.work()
Run
Output:
Completed task_1
Completed task_2
Completed task_3
Consume Less memory: Instance methods are object too, and creating them has a cost.
Having a static method avoids that. Let’s assume you have ten employee objects and if
you create gather_requirement() as a instance method then Python have to create a ten
copies of this method (seperate for each object) which will consume more memeory. On
the other hand static method has only one copy per class.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-static-method%2F 2/4
8/8/22, 8:24 PM Python Static Method Explained With Examples
# false
print(kelly.work is jessa.work)
# True
print(kelly.gather_requirement is jessa.gather_requirement)
# True
print(kelly.gather_requirement is Employee.gather_requirement)
Run
To Write Utility functions: Static methods have limited use because they don’t have
access to the attributes of an object (instance variables) and class attributes (class
variables). However, they can be helpful in utility such as conversion form one type to
another. The parameters provided are enough to operate.
Readabiltity: Seeing the @staticmethod at the top of the method, we know that the
method does not depend on the object’s state or the class state.
You should only use staticmethod() function to define static method if you have to support older
versions of Python (2.2 and 2.3). Otherwise, it is recommended to use the @staticmethod decorator.
Syntax:
staticmethod(function)
Run
function: It is the name of the method you want to convert as a static method.
It returns the converted static method.
Example:
class Employee:
def sample(x):
Employee.sample = staticmethod(Employee.sample)
Employee.sample(10)
Run
The staticmethod() approach is helpful when you need a reference to a function from a class body
and you want to avoid the automatic transformation to the instance method.
@staticmethod
def static_method_1():
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-static-method%2F 3/4
8/8/22, 8:24 PM Python Static Method Explained With Examples
@staticmethod
def static_method_2() :
Test.static_method_1()
@classmethod
def class_method_1(cls) :
cls.static_method_2()
Test.class_method_1()
Run
Output:
static method 1
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-static-method%2F 4/4
8/8/22, 8:25 PM Python Class Method vs. Static Method vs. Instance Method
In Object-oriented programming, when we design a class, we use the following three methods
Instance method performs a set of actions on the data/value provided by the instance
variables. If we use instance variables inside a method, such methods are called instance
methods.
Class method is method that is called on the class itself, not on a specific object
instance. Therefore, it belongs to a class level, and all class instances share a class
method.
Static method is a general utility method that performs a task in isolation. This method
doesn’t have access to the instance and class variable.
Class methods are used as a factory method. Factory methods are those methods that return a class
object for different use cases. For example, you need to do some pre-processing on the provided
data before creating an object.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method-vs-static-method-vs-instance-method%2F 1/5
8/8/22, 8:25 PM Python Class Method vs. Static Method vs. Instance Method
All three methods are defined inside a class, and it is pretty similar to defining a regular
function.
Any method we create in a class will automatically be created as an instance method.
We must explicitly tell Python that it is a class method or static method.
Use the @classmethod decorator or the classmethod() function to define the class
method
Use the @staticmethod decorator or the staticmethod() function to define a static
method.
Example:
Use self as the first parameter in the instance method when defining it. The self
parameter refers to the current object.
On the other hand, Use cls as the first parameter in the class method when defining it.
The cls refers to the class.
A static method doesn’t take instance or class as a parameter because they don’t have
access to the instance variables and class variables.
class Student:
# class variables
# constructor
# instance variables
self.name = name
self.age = age
# instance variables
def show(self):
@classmethod
cls.school_name = name
@staticmethod
def find_notes(subject_name):
Example:
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method-vs-static-method-vs-instance-method%2F 2/5
8/8/22, 8:25 PM Python Class Method vs. Static Method vs. Instance Method
# create object
jessa.show()
Student.change_School('XYZ School')
jessa.change_School('PQR School')
Student.find_notes('Math')
jessa.find_notes('Math')
Run
Output:
Jessa 12 ABC School
The instance method can access both class level and object attributes. Therefore, It can
modify the object state.
Class methods can only access class level attributes. Therefore, It can modify the class
state.
A static method doesn’t have access to the class attribute and instance attributes.
Therefore, it cannot modify the class or object state.
Example:
class Student:
# class variables
self.name = name
self.age = age
# instance method
def show(self):
print('School:', self.school_name)
@classmethod
cls.school_name = name
@staticmethod
def find_notes(subject_name):
# create object
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method-vs-static-method-vs-instance-method%2F 3/5
8/8/22, 8:25 PM Python Class Method vs. Static Method vs. Instance Method
jessa.show()
Student.change_School('XYZ School')
Run
Output:
Student: Jessa 12
Example:
class Student:
# instance method
def show(self):
@classmethod
@staticmethod
def find_notes(subject_name):
jessa = Student(12)
print(jessa.show)
print(jessa.change_school)
print(jessa.find_notes)
Run
Do you know:
In Python, a separate copy of the instance methods will be created for every object.
Suppose you create five Student objects, then Python has to create five copies of the show() method
(separate for each object). So it will consume more memory. On the other hand, the static method
has only one copy per class.
Example:
# create two objects
jessa = Student(12)
kelly = Student(25)
print(jessa.show is kelly.show)
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method-vs-static-method-vs-instance-method%2F 4/5
8/8/22, 8:25 PM Python Class Method vs. Static Method vs. Instance Method
print(jessa.find_notes is kelly.find_notes)
Run
Jessa 20 ABC School
As you can see in the output, the change_School() method is bound to the class.
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-class-method-vs-static-method-vs-instance-method%2F 5/5
8/8/22, 8:26 PM Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
Python Object-oriented programming (OOP) is based on the concept of “objects,” which can
contain data and code: data in the form of instance variables (often known as attributes or
properties), and code, in the form method. I.e., Using OOP, we encapsulate related properties and
behaviors into individual objects.
This OOP classes and objects exercise includes 8 different programs, questions, and challenges. All
solutions are tested on Python 3.
When you complete each question, you get more familiar with the Python OOP. Let us know if you
have any alternative solutions. It will help other developers.
Refer:
Show Solution
OOP Exercise 2: Create a Vehicle class without any variables and methods
Show Solution
OOP Exercise 3: Create a child class Bus that will inherit all of the variables
and methods of the Vehicle class
Given:
class Vehicle:
self.name = name
self.max_speed = max_speed
self.mileage = mileage
Run
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-object-oriented-programming-oop-exercise%2F 1/4
8/8/22, 8:26 PM Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
Create a Bus object that will inherit all of the variables and methods of the parent Vehicle class and
display it.
Expected Output:
Vehicle Name: School Volvo Speed: 180 Mileage: 12
Create a Bus class that inherits from the Vehicle class. Give the capacity argument of
Bus.seating_capacity() a default value of 50.
self.name = name
self.max_speed = max_speed
self.mileage = mileage
Expected Output:
The seating capacity of a bus is 50 passengers
Refer:
Show Hint
Show Solution
OOP Exercise 5: Define a property that must have the same value for every
class instance (object)
Define a class attribute”color” with a default value white. I.e., Every Vehicle should be white.
self.name = name
self.max_speed = max_speed
self.mileage = mileage
class Bus(Vehicle):
pass
class Car(Vehicle):
pass
Run
Expected Output:
Color: White, Vehicle name: School Volvo, Speed: 180, Mileage: 12
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-object-oriented-programming-oop-exercise%2F 2/4
8/8/22, 8:26 PM Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
Show Hint
Show Solution
Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle
is seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a
maintenance charge. So total fare for bus instance will become the final amount = total fare +
10% of the total fare.
Note: The bus seating capacity is 50. so the final fare amount should be 5500. You need to override
the fare() method of a Vehicle class in Bus class.
Use the following code for your parent Vehicle class. We need to access the parent class from
inside a method of a child class.
class Vehicle:
self.name = name
self.mileage = mileage
self.capacity = capacity
def fare(self):
class Bus(Vehicle):
pass
Expected Output:
Total Bus fare is: 5500.0
Show Solution
Given:
class Vehicle:
self.name = name
self.mileage = mileage
self.capacity = capacity
class Bus(Vehicle):
pass
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-object-oriented-programming-oop-exercise%2F 3/4
8/8/22, 8:26 PM Python Object-Oriented Programming (OOP) Exercise: Classes and Objects Exercises
Given:
class Vehicle:
self.name = name
self.mileage = mileage
self.capacity = capacity
class Bus(Vehicle):
pass
read://https_pynative.com/?url=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fpynative.com%2Fpython-object-oriented-programming-oop-exercise%2F 4/4