0% found this document useful (0 votes)
18 views37 pages

Python Oops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views37 pages

Python Oops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

PYTHON OOPS

MODULE 1: Classes and Objects


Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is like
a blueprint for an object.

Some points on Python class:

Classes are created by keyword class. Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot(.) operator. Eg.:
Myclass.Myattribute

Class Definition Syntax:

class ClassName:

# Statement-1

# Statement-N

Defining a class –

# Python3 program to
# demonstrate defining
# a class

class Dog:
pass
In the above example, the class keyword indicates that you are creating a class followed by the
name of the class (Dog in this case).

Class Objects

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of


the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug
who’s seven years old. You can have many dogs to create many different instances, but without
the class as a guide, you would be lost, not knowing what information is required.

An object consists of :

State: It is represented by the attributes of an object. It also reflects the properties of an object.

Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.

Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share
the attributes and the behavior of the class. But the values of those attributes, i.e. the state are
unique for each object. A single class may have any number of instances.

Example:
Declaring an object –

Python3
# Python3 program to
# demonstrate instantiating
# a class

class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code
# Object instantiation
Rodger = Dog()

# Accessing class attributes


# and method through objects
print(Rodger.attr1)
Rodger.fun()

Output
mammal
I'm a mammal
I'm a dog

In the above example, an object is created which is basically a dog named Rodger. This class
only has two class attributes that tell us that Rodger is a dog and a mammal.

The self
Class methods must have an extra first parameter in the method definition. We do not give a
value for this parameter when we call the method, Python provides it.
If we have a method that takes no arguments, then we still have to have one argument.
This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is
about.

__init__method
The __init__ method is similar to constructors in C++ and Java. Constructors are used to
initializing the object’s state. Like methods, a constructor also contains a collection of
statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as
an object of a class is instantiated. The method is useful to do any initialization you want to do
with your object.

Python3
# A Sample class with init method
class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()

Output
Hello, my name is Nikhil

Class and Instance Variables


Instance variables are for data, unique to each instance and class variables are for attributes and
methods shared by all instances of the class. Instance variables are variables whose value is
assigned inside a constructor or method with self whereas class variables are variables whose
value is assigned in the class.

Defining instance variable using a constructor.

Python3
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Dog


class Dog:

# Class Variable
animal = 'dog'

# The init method or constructor


def __init__(self, breed, color):

# Instance Variable
self.breed = breed
self.color = color

# Objects of Dog class


Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")

print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)

print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)

# Class variables can be accessed using class


# name also
print("\nAccessing class variable using class name")
print(Dog.animal)

Output
Rodger details:
Rodger is a dog
Breed: Pug
Color: brown

Buzo details:
Buzo is a dog
Breed: Bulldog
Color: black

Accessing class variable using class name


dog

Accessing class variable using class name


dog
Defining instance variable using the normal method.

Python3
# Python3 program to show that we can create
# instance variables inside methods

# Class for Dog


class Dog:

# Class Variable
animal = 'dog'

# The init method or constructor


def __init__(self, breed):

# Instance Variable
self.breed = breed

# Adds an instance variable


def setColor(self, color):
self.color = color

# Retrieves instance variable


def getColor(self):
return self.color

# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())

Output
Brown

MODULE 2: Constructors in Python


Constructors are generally used for instantiating an object. The task of constructors is to
initialize(assign values) to the data members of the class when an object of the class is
created. In Python the __init__() method is called the constructor and is always called when
an object is created.

Types of constructors :

Default constructor: The default constructor is a simple constructor which doesn’t accept
any arguments. Its definition has only one argument which is a reference to the instance being
constructed.

Parameterized constructor: constructor with parameters is known as parameterized


constructor. The parameterized constructor takes its first argument as a reference to the
instance being constructed known as self and the rest of the arguments are provided by the
programmer.

Example of default constructor :


Example of the parameterized constructor :

________________________________________________________
MODULE 3: Destructors in Python
Destructors are called when an object gets destroyed. In Python, destructors are not needed as much
as in C++ because Python has a garbage collector that handles memory management automatically.

The __del__() method is a known as a destructor method in Python. It is called when all references to
the object have been deleted i.e when an object is garbage collected.

Syntax of destructor declaration :

Note : A reference to objects is also deleted when the object goes out of reference or when the
program ends.

Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all
references of object ‘obj’, therefore destructor invoked automatically.

Note : The destructor was called after the program ended or when all the references to object are
deleted i.e when the reference count becomes zero, not when object went out of scope.

Example 2 :This example gives the explanation of above mentioned note. Here, notice that the
destructor is called after the ‘Program End…’ printed.
Example 3 : Now, consider the following example
In this example when the function fun() is called, it creates an instance of class B which passes itself
to class A, which then sets a reference to class B and resulting in a circular reference.
Generally, Python’s garbage collector which is used to detect these types of cyclic references would
remove it but in this example the use of custom destructor marks this item as “uncollectable”.
Simply, it doesn’t know the order in which to destroy the objects, so it leaves them. Therefore, if your
instances are involved in circular references they will live in memory for as long as the application
run.

Inheritance and their type in Python


Inheritance is the capability of one class to derive or inherit the properties from another class.
The benefits of inheritance are:

It represents real-world relationships well.


It provides reusability of a code. We don’t have to write the same code again and again. Also,
it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A, then all the
subclasses of B would automatically inherit from class A.

Below is a simple example of inheritance in Python.

Python
# code
# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.


# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"

class Person(object):

# Constructor
def __init__(self, name):

self.name = name

# To get name
def getName(self):
return self.name

# To check if this person is an employee


def isEmployee(self):
return False

# Inherited or Subclass (Note Person in bracket)

class Employee(Person):
# Here we return true
def isEmployee(self):

return True

# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee


print(emp.getName(), emp.isEmployee())

Output
('Geek1', False)
('Geek2', True)

What is object class?


Like Java Object class, in Python (from version 3.x), object is root of all classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2.x, “class Test(object)” creates a class with object as parent (called new style class)
and “class Test” creates old style class (without object parent). Refer this for more details.
Subclassing (Calling constructor of parent class)

A child class needs to identify which class is its parent class. This can be done by mentioning
the parent class name in the definition of the child class.

Eg: class subclass_name (superclass_name):

Python
# Python code to demonstrate how parent constructors
# are called.

# parent class

class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber

def display(self):
print(self.name)
print(self.idnumber)

# child class

class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using its instance


a.display()

Output:
Rahul
886012

‘a’ is the instance created for the class Person. It invokes the __init__() of the referred class.
You can see ‘object’ written in the declaration of the class Person. In Python, every class
inherits from a built-in basic class called ‘object’. The constructor i.e. the ‘__init__’ function
of a class is invoked when we create an object variable or an instance of the class.

The variables defined within __init__() are called as the instance variables or objects. Hence,
‘name’ and ‘idnumber’ are the objects of the class Person. Similarly, ‘salary’ and ‘post’ are the
objects of the class Employee. Since the class Employee inherits from class Person, ‘name’
and ‘idnumber’ are also the objects of class Employee.
If you forget to invoke the __init__() of the parent class then its instance variables would not
be available to the child class.

The following code produces an error for the same reason.


Python
# Python program to demonstrate error if we
# forget to invoke __init__() of the parent.

class A:
def __init__(self, n='Rahul'):
self.name = n

class B(A):
def __init__(self, roll):
self.roll = roll

object = B(23)
print(object.name)

Output :
Traceback (most recent call last):
File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in
print (object.name)
AttributeError: 'B' object has no attribute 'name'

Different forms of Inheritance:

1. Single inheritance: When a child class inherits from only one parent class, it is called single
inheritance. We saw an example above.

2. Multiple inheritance: When a child class inherits from multiple parent classes, it is called
multiple inheritance.

Unlike java, python shows multiple inheritance.

Python
# Python example to show the working of multiple
# inheritance

class Base1(object):
def __init__(self):
self.str1 = "Geek1"
print("Base1")

class Base2(object):
def __init__(self):
self.str2 = "Geek2"

print("Base2")

class Derived(Base1, Base2):


def __init__(self):

# Calling constructors of Base1


# and Base2 classes
Base1.__init__(self)
Base2.__init__(self)

print("Derived")

def printStrs(self):
print(self.str1, self.str2)

ob = Derived()
ob.printStrs()

Output
Base1
Base2
Derived

3. Multilevel inheritance: When we have a child and grandchild relationship.

Python
# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.


# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"

class Base(object):

# Constructor
def __init__(self, name):
self.name = name

# To get name
def getName(self):
return self.name

# Inherited or Sub class (Note Person in bracket)


class Child(Base):

# Constructor
def __init__(self, name, age):

Base.__init__(self, name)
self.age = age

# To get name
def getAge(self):
return self.age

# Inherited or Sub class (Note Person in bracket)

class GrandChild(Child):

# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address

# To get address
def getAddress(self):
return self.address

# Driver code
g = GrandChild("Geek1", 23, "Noida")
print(g.getName(), g.getAge(), g.getAddress())

Output
Geek1 23 Noida

4. Hierarchical inheritance : More than one derived classes are created from a single base.
5. Hybrid inheritance: This form combines more than one form of inheritance. Basically, it
is a blend of more than one type of inheritance.
Private members of parent class
We don’t always want the instance variables of the parent class to be inherited by the child
class i.e. we can make some of the instance variables of the parent class private, which won’t
be available to the child class.
We can make an instance variable by adding double underscores before its name. For example,

Python
# Python program to demonstrate private members
# of the parent class

class C(object):

def __init__(self):

self.c = 21

# d is private instance variable


self.__d = 42

class D(C):

def __init__(self):

self.e = 84

C.__init__(self)
object1 = D()

# produces an error as d is private instance variable


print(object1.d)

Output :
File "/home/993bb61c3e76cda5bb67bd9ea05956a1.py", line 16, in
print (object1.d)
AttributeError: type object 'D' has no attribute 'd'

Since ‘d’ is made private by those underscores, it is not available to the child class ‘D’ and
hence the error.

Types of Inheritance

Types of Inheritance depends upon the number of child and parent classes involved. There are
four types of inheritance in Python:
Single Inheritance :Single inheritance enables a derived class to inherit properties from a
single parent class, thus enabling code reusability and the addition of new features to existing
code.

Example:

Python
# Python program to demonstrate
# single inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class

class Child(Parent):
def func2(self):
print("This function is in child class.")

# Driver's code
object = Child()
object.func1()
object.func2()
Multiple Inheritance : When a class can be derived from more than one base class this typeof
inheritance is called multiple inheritance. In multiple inheritance, all the features of the base
classes are inherited into the derived class.

Example:

Python3
# code
# Python program to demonstrate
# multiple inheritance

# Base class1
class Mother:
mothername = ""

def mother(self):
print(self.mothername)

# Base class2

class Father:
fathername = ""

def father(self):
print(self.fathername)

# Derived class

class Son(Mother, Father):


def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)

# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

Output:
Father : RAM
Mother : SITA

Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived class are further inherited
into the new derived class. This is similar to a relationship representing a child and grandfather.
Example:

Python
# code
# Python program to demonstrate
# multilevel inheritance

# Base class

class Grandfather:

def __init__(self, grandfathername):


self.grandfathername = grandfathername

# Intermediate class

class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
# invoking constructor of Grandfather class
Grandfather.__init__(self, grandfathername)

# Derived class

class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname

# invoking constructor of Father class


Father.__init__(self, fathername, grandfathername)

def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)

# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()

Hierarchical Inheritance : When more than one derived classes are created from a single base
this type of inheritance is called hierarchical inheritance. In this program, we have a parent
(base) class and two child (derived) classes.
Example:

Python
# Python program to demonstrate
# Hierarchical inheritance

# Base class
class Parent:
def func1(self):
print("This function is in parent class.")

# Derived class1

class Child1(Parent):
def func2(self):
print("This function is in child 1.")

# Derivied class2

class Child2(Parent):
def func3(self):
print("This function is in child 2.")

# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

Hybrid Inheritance : Inheritance consisting of multiple types of inheritance is called hybrid


inheritance.

Example:

Python
# code
# Python program to demonstrate
# hybrid inheritance

class School:
def func1(self):
print("This function is in school.")

class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School):


def func4(self):
print("This function is in student 3.")

# Driver's code
object = Student3()
object.func1()
object.func2()

Encapsulation in Python
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It
describes the idea of wrapping data and the methods that work on data within one unit. This puts
restrictions on accessing variables and methods directly and can prevent the accidental modification
of data. To prevent accidental change, an object’s variable can only be changed by an object’s
method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member functions,
variables, etc.

Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales section handles all
the sales-related activities and keeps records of all the sales. Now there may arise a situation when for
some reason an official from the finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of the sales section. He will first have to contact
some other officer in the sales section and then request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the employees that can manipulate them are
wrapped under a single name “sales section”. Using encapsulation also hides the data. In this
example, the data of the sections like sales, finance, or accounts are hidden from any other section.
Protected members
Protected members (in C++ and JAVA) are those members of the class that cannot be accessed
outside the class but can be accessed from within the class and its subclasses. To accomplish this in
Python, just follow the convention by prefixing the name of the member by a single underscore “_”.
Although the protected variable can be accessed out of the class as well as in the derived
class(modified too in derived class), it is customary(convention not a rule) to not access the protected
out the class body.

Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated.
Private members
Private members are similar to protected members, the difference is that the class members declared
private should neither be accessed outside the class nor by any base class. In Python, there is no
existence of Private instance variables that cannot be accessed except inside a class.
However, to define a private member prefix the member name with double underscore “__”.
Note:Python’s private and protected members can be accessed outside the class through python name
mangling.
Polymorphism in Python
What is Polymorphism : The word polymorphism means having many forms. In
programming, polymorphism means the same function name (but different signatures) being
used for different types.
Example of inbuilt polymorphic functions :

Python
# Python program to demonstrate in-built poly-
# morphic functions

# len() being used for a string


print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))

Output:
5
3

Examples of user-defined polymorphic functions :

Python
# code
# A simple Python function to demonstrate
# Polymorphism

def add(x, y, z=0):


return x + y+z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))

Output
5
9

Output:
5
9

Polymorphism with class methods :


The below code shows how Python can use two different class types, in the same way. We
create a for loop that iterates through a tuple of objects. Then call the methods without being
concerned about which class type each object is. We assume that these methods actually exist
in each class.

Python
class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Polymorphism with Inheritance :


In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a child class that it has inherited
from the parent class. This is particularly useful in cases where the method inherited from the
parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the
child class. This process of re-implementing a method in the child class is known as Method
Overriding.

Python
class Bird:
def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

Output:
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

Polymorphism with a Function and objects :


It is also possible to create a function that can take any object, allowing for polymorphism. In
this example, let’s create a function called “func()” which will take an object which we will
name “obj”. Though we are using the name ‘obj’, any instantiated object will be able to be
called into this function. Next, let’s give the function something to do that uses the ‘obj’ object
we passed to it. In this case, let’s call the three methods, viz., capital(), language() and type(),
each of which is defined in the two classes ‘India’ and ‘USA’. Next, let’s create instantiations
of both the ‘India’ and ‘USA’ classes if we don’t have them already. With those, we can call
their action using the same func() function:

Python
def func(obj):
obj.capital()
obj.language()
obj.type()

obj_ind = India()
obj_usa = USA()

func(obj_ind)
func(obj_usa)
Code: Implementing Polymorphism with a Function

Python
class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi is the most widely spoken language of India.")

def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

def func(obj):
obj.capital()
obj.language()
obj.type()

obj_ind = India()
obj_usa = USA()

func(obj_ind)
func(obj_usa)

Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Class or Static Variables in Python


All objects share class or static variables. An instance or non-static variables are different for
different objects (every object has a copy). For example, let a Computer Science Student be
represented by class CSStudent. The class may have a static variable whose value is “cse” for all
objects. And class may also have non-static members like name and roll. In C++ and Java, we can use
static keywords to make a variable a class variable. The variables which don’t have a preceding static
keyword are instance variables. See this for the Java example and this for the C++ example.
The Python approach is simple; it doesn’t require a static keyword.
All variables which are assigned a value in the class declaration are class variables. And variables that
are assigned values inside methods are instance variables.
Class method vs Static method in Python
Class Method
The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
after your function is defined. The result of that evaluation shadows your function definition.

A class method receives the class as an implicit first argument, just like an instance method receives
the instance

Syntax:

fun :function that needs to be converted into a class method


returns : a class method for function.
A class method is a method that is bound to the class and not the object of the class.
They have the access to the state of the class as it takes a class parameter that points to the class and
not the object instance.
It can modify a class state that would apply across all the instances of the class. For example, it can
modify a class variable that will be applicable to all the instances.

Static Method
A static method does not receive an implicit first argument.

Syntax:

returns :a static method for function fun.

A static method is also a method that is bound to the class and not the object of the class.
A static method can’t access or modify the class state.
It is present in a class because it makes sense for the method to be present in class.

Class method vs Static Method

1. A class method takes cls as the first parameter while a static method needs no specific
parameters.
2. A class method can access or modify the class state while a static method can’t access or
modify it.
3. In general, static methods know nothing about the class state. They are utility-type methods
that take some parameters and work upon those parameters. On the other hand class methods
must have class as a parameter.
4. We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.

When to use what?


We generally use class method to create factory methods. Factory methods return class objects
( similar to a constructor ) for different use cases.
We generally use static methods to create utility functions.
How to define a class method and a static method?
To define a class method in python, we use @classmethod decorator, and to define a static
method we use @staticmethod decorator.

Let us look at an example to understand the difference between both of them. Let us say we
want to create a class Person. Now, python doesn’t support method overloading like C++ or
Java so we use class methods to create factory methods. In the below example we use a class
method to create a person object from birth year.
As explained above we use static methods to create utility functions. In the below example we
use a static method to check if a person is an adult or not.

Implementation

Python
# Python program to demonstrate
# use of class method and static method.
from datetime import date

class Person:

def __init__(self, name, age):

self.name = name
self.age = age

# a class method to create a Person object by birth year.

@classmethod
def fromBirthYear(cls, name, year):

return cls(name, date.today().year - year)

# a static method to check if a Person is adult or not.

@staticmethod
def isAdult(age):
return age > 18

person1 = Person('mayank', 21)


person2 = Person.fromBirthYear('mayank', 1996)

print(person1.age)
print(person2.age)

# print the result


print(Person.isAdult(22))

Output:

21
25
True

You might also like