0% found this document useful (0 votes)
8 views29 pages

Opps

The document provides an overview of Object-Oriented Programming (OOP) in Python, explaining its core concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It details how objects represent real-world entities with attributes and behaviors, and introduces the syntax for defining classes and creating objects. Additionally, it covers methods, including instance, class, and static methods, along with the use of constructors for object initialization.

Uploaded by

sdharmpal508
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)
8 views29 pages

Opps

The document provides an overview of Object-Oriented Programming (OOP) in Python, explaining its core concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It details how objects represent real-world entities with attributes and behaviors, and introduces the syntax for defining classes and creating objects. Additionally, it covers methods, including instance, class, and static methods, along with the use of constructors for object initialization.

Uploaded by

sdharmpal508
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/ 29

OOPs IN PYTHON

**OOPs** - Object Oriented Programming Structure


This approach is termed as Object Oriented Programming. Object-oriented programming maps our code instructions with real-
world problems, making it easier to write and simpler to understand. They map real-world entities(such as companies and
employees) as 'software objects' that have some 'data' associated with them and can perform some 'functions'.

**In Other Words**

It is a programming technique/paradigm/approach that easily represent/manage real life objects in program.

Python OOPs Concepts


In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in programming. It
aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept
of OOPs is to bind the data and the functions that work on that together as a single unit so that no other part of the code can
access this data.

OOPs Concepts in Python


Class
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction

Python Objects
The object is an entity that has a state and behavior associated with it. It may be any real-world object like a mouse, keyboard,
chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects. More specifically, any
single integer or any single string is an object.
The number 12 is an object, the string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You’ve
been using objects all along and may not even realize it.

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.

**In Other Words**

An object is any entity that has attributes(properties) and behaviors(opration/methods). For example, a parrot is an object.
It has
attributes - name, age, color, etc.
behavior - dancing, singing, etc.

exp:human as object
properties--->age,gender,weight,height
behaviours--->eating(),sleeping(),thinking()
exp:bank account as object
properties--->acn,bal,opendate,type
behaviour---->deposit(),withdraw()
etc.
in memory,object is allocated dynamically.i.e. size of object is not known in advance and we can also manipulate this memory.

in coding,object is an instance of a class.

Python Class
A class is a template/design/blueprint for creating similar objects(instances).
A class also represent a datatype.

In [ ]:
In [1]: # Class represents a data type

x = 10
print(type(x))

y = []
print(type(y))

z = "Hello World"
print(type(z))

<class 'int'>
<class 'list'>
<class 'str'>

In [ ]:

Syntax to define Class in Python

class Classname
code

Recommendation to define class name, first letter should be in upper case. But it is not necessary.

In [2]: # Creating a class of 'Account'


class Account:
pass

# Creating a class of 'Employee'


class Employee:
pass

In [ ]:

Syntax to create an Object

1. Explicit approach using class name -


RefVar = Classname() # Object created and stored in a refrence variable

Note :- If we don't store object into a variable then we will lose the object and we can't use this object in the further programm, this
type of object is called unreachable/anonymous object .

2. implicit approach using literal -

* With quotation mark("",'','''''',"""""") - string object


* With any integer - int object
* With any float - float object
* With any list - list object
* etc

Note :- Implicit approach is only for specific classes like int,float,dict,list,etc.

If we print refrance variable wich stored an object then it will return the address of the object.

In [3]: #Creating a class of account


class account:
pass

#Creating a class of employee


class employee:
pass

#Creating an object of account


a1=account()

#Creating another object of account


a2=account()

#Creating an object of employee


e1=employee()

#Printing refrence variable where object stored


print(a1)
print(a2)
print(e1)
<__main__.account object at 0x0000026BCB99F050>
<__main__.account object at 0x0000026BCB99D190>
<__main__.employee object at 0x0000026BCB99D690>

In [ ]:

Sytax to call any methode of a class :


1. First create an object of a class :

RefVar = ClassName()

2. Then :

object.method()

Where
object = RefVar
method = function defined in the class

In [ ]:

Observe the below code and error :

In [4]: class test:


def show():
print("this is show method")

t1=test()
t1.show() #by interpreter--->t1.show(t1,10)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 6
3 print("this is show method")
5 t1=test()
----> 6 t1.show()

TypeError: test.show() takes 0 positional arguments but 1 was given


In [ ]:

To solve above error we have to use self keyword as first parameter of show methode :

In [5]: class test:


def show(self):
print("this is show method")

t1=test()
t1.show() #by interpreter--->t1.show(t1,10)

this is show method

In [ ]:

The self Parameter :


The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

Note :- It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in
the class.

Que.: How to create an object and call a method of created object of a class of any module?

First we have import module.


Then we have to create an object with following syntax :
object = module_name.class_name()
Then call the method of a class using following syntax :
object.methode_name()
Example : Let their is test module in library and we m1 is the methode of abc class in test module.

In [6]: # importing test module


import test

# Creating object of abc class of test module


obj = test.abc()

# Calling the m1 method of abc class


obj.m1()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[6], line 5
2 import test
4 # Creating object of abc class of test module
----> 5 obj = test.abc()
7 # Calling the m1 method of abc class
8 obj.m1()

AttributeError: module 'test' has no attribute 'abc'

In [ ]:

Object Initialization :
__init__() method in Python is used to initialize objects of a class. It is also called a constructor.
The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created.
Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object
creation. It is run 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.
The __init__() method acts as a constructor. It needs a mandatory argument self, which the reference to the object.

In [7]: class Account:


def __init__(self):
print("This is 'Constructor'")
a1 = Account() #by interpreter--->a1=Account() ; a1.__init__(a1)
a2 = Account() #by interpreter--->a1=Account() ; a1.__init__(a1)
a1.__init__() #not recommended

This is 'Constructor'
This is 'Constructor'
This is 'Constructor'

In [ ]:

In [8]: class Account:


def __init__(self):
self.acn=101
self.bal=1000

a1=Account()
a2=Account()
print(a1.acn,a1.bal)
print(a2.acn,a2.bal)

101 1000
101 1000

In [ ]:

In [9]: class Account:


def __init__(self,a,b):
self.acn=a
self.bal=b

a1=Account(101,1000)
a2=Account(102,2000)
print(a1.acn,a1.bal)
print(a2.acn,a2.bal)

101 1000
102 2000

In [ ]:

In [10]: class Account:


def __init__(self,a,b):
self.acn=a
self.bal=b

def deposit(self):
self.bal=self.bal+500

a1=Account(101,1000)
a2=Account(102,2000)
print(a1.acn,a1.bal)
print(a2.acn,a2.bal)

a1.deposit()
a2.deposit()
print(a1.acn,a1.bal)
print(a2.acn,a2.bal)
101 1000
102 2000
101 1500
102 2500

In [ ]:

In [11]: class Account:


def __init__(self,a,b):
self.acn=a
self.bal=b

def deposit(self,amt):
self.bal=self.bal+amt

def withdraw(self,amt):
if(self.bal>amt):
self.bal=self.bal-amt
else:
print("insufficient fund")

def checkbal(self):
print(self.acn,self.bal)

a1=Account(101,1000)
a2=Account(102,2000)

a1.checkbal()
a2.checkbal()

a1.withdraw(50)
a2.withdraw(10000)

a1.checkbal()
a2.checkbal()

101 1000
102 2000
insufficient fund
101 950
102 2000

In [ ]:
Type of data members :
- instance data members --> allocated for each object
- class data members --> allocated for class and shared to all objects.

In [12]: class Account:

ifsc="abc123" #class data member

def __init__(self,a,b):
#instance data members
self.acn=a
self.bal=b

def deposit(self,amt):
self.bal=self.bal+amt

def withdraw(self,amt):
if(self.bal>amt):
self.bal=self.bal-amt
else:
print("insufficient fund")

def checkbal(self):
print(self.acn,self.bal,self.ifsc)

a1=Account(101,1000)
a2=Account(102,2000)
a1.checkbal()
a2.checkbal()

a1.deposit(500)
a2.deposit(200)

a1.checkbal()
a2.checkbal()

a1.withdraw(50)
a2.withdraw(10000)

a1.checkbal()
a2.checkbal()
101 1000 abc123
102 2000 abc123
101 1500 abc123
102 2200 abc123
insufficient fund
101 1450 abc123
102 2200 abc123

In [ ]:

Syntax to change class data member value :

Classname.data_member = value

In [13]: class Account:

ifsc="abc123" #class data member

def __init__(self,a,b):
#instance data members
self.acn=a
self.bal=b

def deposit(self,amt):
self.bal=self.bal+amt

def withdraw(self,amt):
if(self.bal>amt):
self.bal=self.bal-amt
else:
print("insufficient fund")

def checkbal(self):
print(self.acn,self.bal,self.ifsc)

a1=Account(101,1000)
a2=Account(102,2000)

a1.checkbal()
a2.checkbal()

Account.ifsc="pqr321"
a1.checkbal()
a2.checkbal()

101 1000 abc123


102 2000 abc123
101 1000 pqr321
102 2000 pqr321

In [ ]:

Type of Methods :
1. Instance method
1. class method
1. static method

In [14]: class test:


def m1(self): #instance method
print("this is m1")

@classmethod
def m2(cls): #class method
print("this is m2")

@staticmethod
def m3(): #static method
print("this is m3")

t=test()
t.m1() #t.m1(t)
test.m2() #test.m2(test)
test.m3() #test.m3()

this is m1
this is m2
this is m3

In [ ]:

1. Instance Method :
Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute.
Example :

In [15]: class calculator:


def __init__(self):
self.a=4
self.b=5

def mul(self):
print(self.a*self.b)

obj=calculator()
obj.mul()

20

In [ ]:

2. Class method :
It is one of the rarely used methods, where we use cls instead of self and we use class variables.
@ classmethod → constructor which we use as a decorator to make a class methode.

Example :

In [16]: class calculator:


a=4
b=5

@classmethod
def mul(cls):
print(cls.a*cls.b)

calculator.mul()

20

In [17]: class calculator:


a=4
b=5

@classmethod
def mul(cls):
print(calculator.a*calculator.b)
calculator.mul()

20

In [ ]:

Static method :
In this method, we can pass generic variables in the place of self where we can use it like defining functions normally, as you have
to pass the arguments while calling it.
@ staticmethod → constructor which we use as a decorator to make a static methode.

Example :

In [18]: class calculator:

@staticmethod
def mul(a,b):
print(a*b)

calculator.mul(4,5)

20

In [ ]:

Nested Class :
A class is said to be Nested Class , if it's defined inside other class.

In [19]: class A: # Outer/Enclosing/Top level class


class B: # Inner/Nested class
pass

In [ ]:

Sytax to create an object of nested class :


1. Creating nested class object with the help of outer class object :
In [20]: # Creating a nested class
class Outer:
def show(self):
print("Method Of Outer Class")
class Inner:
def disp(self):
print("Method Of Inner Class")
# Creating outer class object
out_obj = Outer()

# Creating inner class object using inner class object


in_obj = out_obj.Inner()

# Now we can call the method of inner class


in_obj.disp()

Method Of Inner Class

In [ ]:

2. Creating nested class object without creating of outer class object :

In [21]: # Creating a nested class


class Outer:
def show(self):
print("Method Of Outer Class")
class Inner:
def disp(self):
print("Method Of Inner Class")

# Directly creating inner class object.


in_obj = Outer().Inner()

# Now we can call the method of inner class


in_obj.disp()

Method Of Inner Class

In [22]: # Creating a nested class


class Outer:
def show(self):
print("Method Of Outer Class")
class Inner:
def disp(self):
print("Method Of Inner Class")

# Directly creating inner class object.


in_obj = Outer.Inner()

# Now we can call the method of inner class


in_obj.disp()

Method Of Inner Class

In [ ]:

Que. Why Inner Classes?

1. Grouping of two or more classes. Suppose you have two classes Car and Engine. Every Car needs an Engine. But, Engine won't be
used without a Car. So, you make the Engine an inner class to the Car. It helps save code.

2. Hiding code is another use of Nested classes. You can hide the Nested classes from the outside world.

3. It's easy to understand the classes. Classes are closely related here. You don't have to search for the classes in the code. They are
all together.

Inner or Nested classes are not the most commonly used feature in Python. But, it can be a good feature to implement code. The
code is straightforward to organize when you use the inner or nested classes.

In [23]: #inner class example


class Person:
def __init__(self):
self.name = 'Karthik'
self.db = self.Dob()
def display(self):
print('Name=', self.name)
class Dob:
def __init__(self):
self.dd = 10
self.mm = 5
self.yy = 1988
def display(self):
print('Dob= {}/{}/{}'.format(self.dd, self.mm, self.yy))
p = Person()
p.display()
x = p.db
x.display()

Name= Karthik
Dob= 10/5/1988

In [ ]:

There are four pillars(fundamental concepts) of OOPs :


1. Inheritance,
2. Data Encapsulation
3. Polymorphism
4. Data Abstraction

1. Inheritance :
Inheritance is the procedure in which one class inherits the attributes and methods of another class.

The class whose properties and methods are inherited is known as the Parent class . And the class that inherits the properties from
the parent class is the Child class .

Types Of Inheritance :

a.) Single level :- 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.

b.) Multilevel :- 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 a grandfather.

c.) Multiple :- When a class can be derived from more than one base class this type of inheritance is called multiple inheritances.

d.) Hybrid :- Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

e.) Hierarchical :- When more than one derived class 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.

In [24]: # 1. 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()

This function is in parent class.


This function is in child class.

In [ ]:

In [25]: # 2. 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()

Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince

In [ ]:

In [26]: # 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()
Father : RAM
Mother : SITA

In [ ]:

In [27]: # 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()

This function is in school.


This function is in student 1.

In [ ]:

In [28]: # 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()

This function is in parent class.


This function is in child 1.
This function is in parent class.
This function is in child 2.

In [ ]:

Key points about inheritance in Python

object class is the top most base class for all python classes directly or indirectly.
incase of method conflict,MRO technique is used to resolve method call.

In [29]: print("Total Methods in Object Class : ",len(dir(object)),"\n",dir(object),sep = "")

Total Methods in Object Class : 30


['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '_
_getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new
__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref_
_', 'func1', 'func2', 'func4']

In [ ]:

2. Data Encapsulation :
Encapsulation is the process of making data private by wrapping data and its methods in a 'capsule' or unit, so that it can not be
accessed or modified outside of that unit.

This is achieved by making variables private inside a class. In Python we can make variables private by prefixing the variable name
with a double underscore __ . Now data is private, and cannot be modified or changed from outside the class.
In [30]: #without encapsulation
class emp:
def __init__(self):
self.sal=20000

e=emp()
print(e.sal)
e.sal=0
print(e.sal)

20000
0

In [31]: #with encapsulation


class emp:
def __init__(self):
self.__sal=20000 # private

# getVarName(self) ----> to give access of data


# Note - after get, VarName must be without underscore. See getsal(self) method for example.

def getsal(self):
if(True):
return self.__sal
else:
return 0
e=emp()
#print(e.__sal) # it will raise an error because we made data private
print(e.getsal()) # we can still access through getsal method of class.

20000

In [ ]:

3. Polymorphism :
Single entity in a programming language can behave in multiple ways depending on the context.

In Python,we implement polymorphism in following 2 ways:


1. Method Overriding
2. Operator Overloading ##### 1. Method Overriding In inheritance, if we redefine a method of parent class in child class then
this concept is known as Method Overriding.
In [32]: class Sachin:
def play(self):
print("full time batsman and part time bowler")

class Arjun(Sachin):
def play(self):
print("full time bowler and part time batsman")

obj=Arjun()
obj.play()

full time bowler and part time batsman

In [33]: class person:


def eating(self):
print("daal roti")

def morningwalk(self):
print("5 km daily")

def study(self):
print("using candle,diya,lamp")

class child(person):
def dance(self):
print("this is dance")

def study(self):
print("zoom,youtube,google")

def eating(self):
print("pizza burger")
super().eating() # super() is explaine below of this program.

obj=child()
obj.dance()
obj.eating()
obj.study()

obj=person()
obj.study()
this is dance
pizza burger
daal roti
zoom,youtube,google
using candle,diya,lamp

In [ ]:

super() function :

In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass
from the subclass, enabling you to extend and customize the functionality inherited from the parent class.

In [ ]:

2. Operator Overloading :
Operator polymorphism, or operator overloading, means that one symbol can be used to perform multiple operations.

In [34]: class Point:


def __init__(self,a,b):
self.x = a
self.y = b

# Overloading the '+' operator


def __add__(self,other):
return self.x+other.x,self.y+other.y

# Overloading the '*' operator


def __mul__(self,other):
return self.x*other.x,self.y*other.y

#Creating p1 and p2 objects of Point class.


p1 = Point(4,5)
p2 = Point(2,1)

# Printing the result of '+' and '*' operators for own purpose.
print(p1+p2) # by interpreter--->p1.__add__(p1,p2)
print(p1*p2) # by interpreter--->p1.__mul__(p1,p2)

(6, 6)
(8, 5)
In [ ]:

4. Abstraction In OOP:
Abstraction in python is defined as a process of handling complexity by hiding unnecessary information from the user. This is one
of the core concepts of object-oriented programming (OOP) languages.

Abstraction In Python
it is a process of defining abstract classes.
it is used to define standards for concrete classes.

Abstract Class :

A class that contains one or more abstract methods is called an abstract class. And the sub class of ABC in Python. An abstract
class can be considered a blueprint for other classes.

We can not make object of abstract class.

Abstract Method :

An abstract method is a method that has a declaration but does not have an implementation.

Use Of Abstract Class :

We use an abstract class while we are designing large functional units or when we want to provide a common interface for
different implementations of a component.

Achieving Abstraction in Python :

In Python, abstraction can be achieved by having/using abstract classes and methods in our programs.

An abstract class is defined by subclassing ABC Python and declaring one or more abstract methods using the
@abstractmethod decorator.

In [35]: # First import 'ABC' class and abstractmethod decorator from abc module.
from abc import ABC,abstractmethod

# Define a class which will be the sub class of ABC class.


class Test(ABC):
# Define abstract method. It may be one or more method.
@abstractmethod #---> abstract decorator
def show(self): #---> should be undefined method
pass

# We may or may not defined concrete method.


def disp(self):
print("This is disp.")

# All above code is the example to make an abstract class.

# To access all the variable and methods of abstract class we


# need to define a child class of abstract and override the
# method of abstract class.

# Defining a child class of abstract class :


class Other(Test):

# overriding abstract method


def show(self):
print("This is show.")

# Now we can access variable and method of abstract class


# through child class object.
obj = Other()
obj.show()
obj.disp()

This is show.
This is disp.

In [ ]:

Example : Defining a blue print for SavingAccount class and CurrentAccount class through Account class which is an abstract
class.

In [36]: class Account(ABC):

@abstractmethod
def deposit(self):
pass

@abstractmethod
def withdraw(self):
pass

@abstractmethod
def checkbal(self):
pass

class SavingAccount(Account):
def deposit(self):
print("this is deposit in saving")
def withdraw(self):
print("this is withdraw in saving")
def checkbal(self):
print("this is checkbal in saving")

class CurrentAccount(Account):
def deposit(self):
print("this is deposit in current")
def withdraw(self):
print("this is withdraw in current")
def checkbal(self):
print("this is checkbal in current")

a1=SavingAccount()
a1.deposit()

a2=CurrentAccount()
a2.deposit()

this is deposit in saving


this is deposit in current

In [ ]:

Example : This code defines an abstract base class called Polygon using the ABC (Abstract Base Class) module in Python. The
Polygon class has an abstract method called noofsides that needs to be implemented by its subclasses.

In [37]: # Python program showing


# abstract base class work
from abc import ABC, abstractmethod

class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass

class Triangle(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 3 sides")

class Pentagon(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 5 sides")

class Hexagon(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 6 sides")

class Quadrilateral(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 4 sides")

# Driver code
R = Triangle()
R.noofsides()

K = Quadrilateral()
K.noofsides()

R = Pentagon()
R.noofsides()

K = Hexagon()
K.noofsides()
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides

In [ ]:

You might also like