0% found this document useful (0 votes)
35 views16 pages

Python OOPs Concepts

grtgr
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
35 views16 pages

Python OOPs Concepts

grtgr
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

will gives you insights of Python

Python OOPs programming


Concepts OOPs Concepts in
Python
Object Oriented Programming is a  Class in Python
fundamental concept in Python,  Objects in Python
empowering developers to build  Polymorphism in Python
modular, maintainable, and  Encapsulation in Python
scalable applications. By  Inheritance in Python
understanding the core OOP  Data Abstraction in Python
principles—classes, objects,
inheritance, encapsulation, Python Class
polymorphism, and abstraction— A class is a collection of objects. A
programmers can leverage the full class contains the blueprints or the
potential of Python’s OOP prototype from which the objects
capabilities to design elegant and are being created. It is a logical
efficient solutions to complex entity that contains some attributes
problems. and methods.
What is Object-Oriented To understand the need for
Programming in creating a class let’s consider an
example, let’s say you wanted to
Python? track the number of dogs that may
In Python object-oriented have different attributes like breed,
Programming (OOPs) is a and age. If a list is used, the first
programming paradigm that uses element could be the dog’s breed
objects and classes in while the second element could
programming. It aims to implement represent its age. Let’s suppose
real-world entities like inheritance, there are 100 different dogs, then
polymorphisms, encapsulation, etc. how would you know which
in the programming. The main element is supposed to be which?
concept of object-oriented What if you wanted to add other
Programming (OOPs) or oops properties to these dogs? This
concepts in Python is to bind the lacks organization and it’s the
data and the functions that work exact need for classes.
together as a single unit so that no Some points on Python class:
other part of the code can access  Classes are created by keyword
this data. For more in-depth class.
knowledge in Python OOPs  Attributes are the variables that
concepts, try belong to a class.
GeeksforGeeks Python course, it
 Attributes are always public and An object consists of:
can be accessed using the dot  State: It is represented by the
(.) operator. Eg.: attributes of an object. It also
Myclass.Myattribute reflects the properties of an
Class Definition Syntax: object.
class ClassName:  Behavior: It is represented by
# Statement-1 the methods of an object. It also
. reflects the response of an
.
object to other objects.
.
 Identity: It gives a unique name
# Statement-N
Creating an Empty Class in to an object and enables one
object to interact with other
Python objects.
In the above example, we have To understand the state, behavior,
created a class named Dog using and identity let us take the example
the class keyword. of the class dog (explained
above).
 The identity can be considered
# Python3 program to
as the name of the dog.
# demonstrate defining
 State or Attributes can be
# a class
considered as the breed, age, or
class Dog: color of the dog.
pass  The behavior can be considered
Python Objects as to whether the dog is eating
In object oriented programming or sleeping.
Python, The object is an entity that Creating an Object
has a state and behavior This will create an object named
associated with it. It may be any obj of the class Dog defined above.
real-world object like a mouse, Before diving deep into objects and
keyboard, chair, table, pen, etc. classes let us understand some
Integers, strings, floating-point basic keywords that will be used
numbers, even arrays, and while working with objects and
dictionaries, are all objects. More classes.
specifically, any single integer or obj = Dog()
any single string is an object. The The Python self
number 12 is an object, the string 1. Class methods must have an
“Hello, world” is an object, a list is extra first parameter in the
an object that can hold other method definition. We do not
objects, and so on. You’ve been give a value for this parameter
using objects all along and may not when we call the method,
even realize it. Python provides it
2. If we have a method that takes print("Rodger is a
no arguments, then we still have {}".format(Rodger.__class__.attr1
))
to have one argument. print("Tommy is also a
3. This is similar to this pointer in {}".format(Tommy.__class__.attr1)
C++ and this reference in Java. )
When we call a method of this
object as myobject.method(arg1, # Accessing instance attributes
arg2), this is automatically print("My name is
{}".format(Rodger.name))
converted by Python into print("My name is
MyClass.method(myobject, arg1, {}".format(Tommy.name))
arg2) – this is all the special self is
about. Output
Note: For more information, refer
to self in the Python class Rodger is a mammal
The Python __init__ Method
Tommy is also a mammal
The __init__ method is similar to
constructors in C++ and Java. It is My name is Rodger
run as soon as an object of a class My name is Tommy
is instantiated. The method is
useful to do any initialization you Creating Classes and objects
want to do with your object. Now let with methods
us define a class and create some Here, The Dog class is defined with
objects using the self and __init__ two attributes:
method.  attr1 is a class attribute set to
Creating a class and object the value “mammal“. Class
with class and instance attributes are shared by all
attributes instances of the class.
 __init__ is a special method
class Dog:
(constructor) that initializes an
# class attribute instance of the Dog class. It
attr1 = "mammal" takes two parameters: self
(referring to the instance being
# Instance attribute created) and name
def __init__(self, name): (representing the name of the
self.name = name dog). The name parameter is
used to assign a name attribute
# Driver code
# Object instantiation to each instance of Dog.
Rodger = Dog("Rodger") The speak method is defined
Tommy = Dog("Tommy") within the Dog class. This
method prints a string that
# Accessing class attributes
includes the name of the dog capability of one class to derive or
instance. inherit the properties from another
The driver code starts by creating class. The class that derives
two instances of the Dog class: properties is called the derived
Rodger and Tommy. The __init__ class or child class and the class
method is called for each instance from which the properties are being
to initialize their name attributes derived is called the base class or
with the provided names. The parent class. The benefits of
speak method is called in both inheritance are:
instances (Rodger.speak() and  It represents real-world
Tommy.speak()), causing each dog relationships well.
to print a statement with its name.  It provides the reusability of a
Python code. We don’t have to write the
class Dog: same code again and again.
Also, it allows us to add more
# class attribute
attr1 = "mammal"
features to a class without
modifying it.
# Instance attribute  It is transitive in nature, which
def __init__(self, name): means that if class B inherits
self.name = name from another class A, then all
the subclasses of B would
def speak(self):
print("My name is
automatically inherit from class
{}".format(self.name)) A.
Types of Inheritance
# Driver code  Single Inheritance: Single-level
# Object instantiation inheritance enables a derived
Rodger = Dog("Rodger") class to inherit characteristics
Tommy = Dog("Tommy")
from a single-parent class.
# Accessing class methods  Multilevel Inheritance: Multi-
level inheritance enables a
derived class to inherit
Rodger.speak() properties from an immediate
Tommy.speak() parent class which in turn
inherits properties from his
parent class.
Output
My name is Rodger  Hierarchical
Inheritance: Hierarchical-level
My name is Tommy inheritance enables more than
one derived class to inherit
Python Inheritance properties from a parent class.
In Python object oriented
Programming, Inheritance is the
 Multiple Inheritance: Multiple- def __init__(self, name,
level inheritance enables one idnumber, salary, post):
self.salary = salary
derived class to inherit
self.post = post
properties from more than one
base class. # invoking the __init__
Inheritance in Python of the parent class
In the above article, we have Person.__init__(self,
name, idnumber)
created two classes i.e. Person
(parent class) and Employee (Child def details(self):
Class). The Employee class print("My name is
inherits from the Person class. We {}".format(self.name))
can use the methods of the person print("IdNumber:
class through the employee class {}".format(self.idnumber))
print("Post:
as seen in the display function in {}".format(self.post))
the above code. A child class can
also modify the behavior of the
parent class as seen through the # creation of an object variable
details() method. or an instance
# Python code to demonstrate how a = Employee('Rahul', 886012,
parent constructors 200000, "Intern")
# are called.
# calling a function of the class
# parent class Person using
class Person(object): # its instance
a.display()
# __init__ is known as the a.details()
constructor
def __init__(self, name, Output
idnumber): Rahul
self.name = name
self.idnumber = idnumber 886012
My name is Rahul
def display(self):
print(self.name) IdNumber: 886012
print(self.idnumber)
Post: Intern
def details(self):
print("My name is Python Polymorphism
{}".format(self.name)) In object oriented Programming
print("IdNumber: Python, Polymorphism simply
{}".format(self.idnumber)) means having many forms. For
# child class
example, we need to determine if
class Employee(Person): the given species of birds fly or not,
using polymorphism we can do this obj_ost.flight()
using a single function.
Polymorphism in Python Output
This code demonstrates the There are many types of
concept of Python oops inheritance birds.
and method overriding in Python Most of the birds can fly but
classes. It shows how subclasses some cannot.
can override methods defined in There are many types of
their parent class to provide birds.
specific behavior while still
inheriting other methods from the Sparrows can fly.
parent class. There are many types of
Python birds.
class Bird:
Ostriches cannot fly.
def intro(self):
Note: For more information, refer
print("There are many
types of birds.") to our Polymorphism in
Python Tutorial.
def flight(self): Python Encapsulation
print("Most of the birds
In Python object oriented
can fly but some cannot.")
programming, Encapsulation is one
class sparrow(Bird): of the fundamental concepts in
object-oriented programming
def flight(self): (OOP). It describes the idea of
print("Sparrows can wrapping data and the methods
fly.")
that work on data within one unit.
class ostrich(Bird): This puts restrictions on accessing
variables and methods directly and
def flight(self): can prevent the accidental
print("Ostriches cannot modification of data. To prevent
fly.") accidental change, an object’s
variable can only be changed by an
obj_bird = Bird()
obj_spr = sparrow()
object’s method. Those types of
obj_ost = ostrich() variables are known as private
variables.
obj_bird.intro() A class is an example of
obj_bird.flight() encapsulation as it encapsulates all
the data that is member functions,
obj_spr.intro()
obj_spr.flight()
variables, etc.

obj_ost.intro()
Encapsulation in Python
In the above example, we have Output
created the c variable as the GeeksforGeeks
private attribute. We cannot even
Note: for more information, refer to
access this attribute directly and
our Encapsulation in
can’t even change its value.
Python
Python Tutorial.
# Python program to Data Abstraction
# demonstrate private members It hides unnecessary code details
# "__" double underscore from the user. Also, when we do
represents private attribute.
# Private attributes start with
not want to give out sensitive parts
"__". of our code implementation and
this is where data abstraction
# Creating a Base class came.
class Base: Data Abstraction in Python can be
def __init__(self):
achieved by creating abstract
self.a = "GeeksforGeeks"
self.__c = classes.
"GeeksforGeeks" Object Oriented Programming in
Python | Set 2 (Data Hiding and
# Creating a derived class Object Printing)
class Derived(Base):
def __init__(self):
Python OOPs – FAQs
What are the 4 pillars of OOP
# Calling constructor of Python?
# Base class
Base.__init__(self)
The 4 pillars of object-oriented
print("Calling private programming (OOP) in Python
member of base class: ") (and generally in programming)
print(self.__c) are:
 Encapsulation: Bundling data
(attributes) and methods
# Driver code
obj1 = Base()
(functions) that operate on the
print(obj1.a) data into a single unit (class).
 Abstraction: Hiding complex
# Uncommenting print(obj1.c) will implementation details and
# raise an AttributeError providing a simplified interface.
 Inheritance: Allowing a class to
# Uncommenting obj2 = Derived()
inherit attributes and methods
will
# also raise an AtrributeError as from another class, promoting
# private member of base class code reuse.
# is called inside derived class
 Polymorphism: Using a single useful for accessing inherited
interface to represent different methods that have been overridden
data types or objects. in a subclass.
Is OOP used in Python? class
ChildClass(ParentClass):
Yes, Python fully supports object-
def __init__(self, arg1,
oriented programming (OOP) arg2):
concepts. Classes, objects,
inheritance, encapsulation, and super().__init__(arg1) #
polymorphism are fundamental Calls the __init__() method
features of Python. of the ParentClass
Is Python 100% object- self.arg2 = arg2
oriented? Why is self used in Python?
'self' is a convention in Python
Python is a multi-paradigm
programming language, meaning it used to refer to the instance of
supports multiple programming a class (object) itself. It’s the first
paradigms including procedural, parameter of instance methods and
functional, and object-oriented refers to the object calling the
programming. While Python is method. It allows methods to
predominantly object-oriented, it access and manipulate attributes
also allows for procedural and (variables) that belong to the
functional programming styles. instance.
class MyClass:
What is __init__ in Python? def __init__(self, name):
__init__ is a special method self.name = name
(constructor) in Python classes. It’s
automatically called when a new def greet(self):
instance (object) of the class is return f"Hello,
created. Its primary purpose is to {self.name}!"
initialize the object’s attributes or
obj = MyClass("Alice")
perform any setup required for the print(obj.greet()) # Output:
object. Hello, Alice!
class MyClass:
def __init__(self, arg1,
arg2): Python Functions
self.arg1 = arg1
self.arg2 = arg2 Last Updated : 29 Jul, 2024
What is super() in Python?

super() is used to call methods of 
a superclass (parent class) from a 
subclass (child class). It returns a
proxy object that delegates method Python Functions is a block
calls to the superclass. This is of statements that return the
specific task. The idea is to put following example, we can
some commonly or repeatedly understand how to write a
done tasks together and make function in Python. In this way
a function so that instead of we can create Python function
writing the same code again definition by using def
and again for different inputs, keyword.
we can do the function calls to Python
reuse code contained in it over # A simple Python function
and over again. def fun():
Some Benefits of Using print("Welcome to GFG")
Functions Calling a Function in
 Increase Code Readability Python
 Increase Code Reusability After creating a function in
Python Function Python we can call it by using
the name of the functions
Declaration Python followed by parenthesis
The syntax to declare a containing parameters of that
function is: particular function. Below is the
example for calling def function
Syntax of Python Function Declaration Python.
Python
Types of Functions in # A simple Python function
def fun():
Python print("Welcome to GFG")
Below are the different types of
functions in Python:
 Built-in library # Driver code to call a function
fun()
function: These
are Standard functions in Output:
Welcome to GFG
Python that are available to
use.
Python Function with
 User-defined function: We
can create our own functions Parameters
based on our requirements. If you have experience in C/C++ or
Creating a Function Java then you must be thinking
about the return type of the
in Python function and data type of
We can define a function in arguments. That is possible in
Python, using the def keyword. Python as well (specifically for
We can add any type of Python 3.5 and above).
functionalities and properties
to it as we require. By the
Python Function Syntax with Output:
Parameters False True
def function_name(parameter: Python Function
data_type) -> return_type:
"""Docstring""" Arguments
# body of the function Arguments are the values passed
return expression inside the parenthesis of the
The following example function. A function can have any
uses arguments and number of arguments separated by
parameters that you will learn later a comma.
in this article so you can come In this example, we will create a
back to it again if not understood. simple function in Python to check
Python whether the number passed as an
def add(num1: int, num2: int) -> argument to the function is even or
int:
"""Add two numbers"""
odd.
Python
num3 = num1 + num2
# A simple Python function to
check
return num3
# whether x is even or odd
def evenOdd(x):
# Driver code
if (x % 2 == 0):
num1, num2 = 5, 15
print("even")
ans = add(num1, num2)
else:
print(f"The addition of {num1} and
print("odd")
{num2} results {ans}.")
Output:
The addition of 5 and 15 # Driver code to call the function
results 20. evenOdd(2)
Note: The following examples are evenOdd(3)
defined using syntax 1, try to Output:
convert them in syntax 2 for even
practice. odd
Python Types of Python Function
# some more functions Arguments
def is_prime(n):
if n in [2, 3]: Python supports various types of
return True arguments that can be passed at
if (n == 1) or (n % 2 == 0): the time of the function call. In
return False Python, we have the following
r = 3
function argument types in Python:
while r * r <= n:
if n % r == 0:  Default argument
return False  Keyword arguments (named
r += 2 arguments)
return True  Positional arguments
print(is_prime(78), is_prime(79))
 Arbitrary arguments (variable-
length arguments *args and
**kwargs) # Keyword arguments
student(firstname='Geeks',
Let’s discuss each type in detail. lastname='Practice')
Default Arguments
student(lastname='Practice',
A default argument is a parameter firstname='Geeks')
that assumes a default value if a Output:
value is not provided in the function Geeks Practice
call for that argument. The Geeks Practice
following example illustrates Positional Arguments
Default arguments to write We used the Position
functions in Python. argument during the function call
Python so that the first argument (or value)
# Python program to demonstrate is assigned to name and the
# default arguments
def myFun(x, y=50):
second argument (or value) is
print("x: ", x) assigned to age. By changing the
print("y: ", y) position, or if you forget the order
of the positions, the values can be
used in the wrong places, as
# Driver code (We call myFun() shown in the Case-2 example
with only
below, where 27 is assigned to the
# argument)
myFun(10) name and Suraj is assigned to the
Output: age.
x: 10 Python
y: 50 def nameAge(name, age):
print("Hi, I am", name)
Like C++ default arguments, any print("My age is ", age)
number of arguments in a function
can have a default value. But once
we have a default argument, all the # You will get correct output
arguments to its right must also because
have default values. # argument is given in order
Keyword Arguments print("Case-1:")
nameAge("Suraj", 27)
The idea is to allow the caller to # You will get incorrect output
specify the argument name with because
values so that the caller does not # argument is not in order
need to remember the order of print("\nCase-2:")
parameters. nameAge(27, "Suraj")
Python Output:
# Python program to demonstrate Case-1:
Keyword Arguments Hi, I am Suraj
def student(firstname, lastname): My age is 27
print(firstname, lastname) Case-2:
Hi, I am 27
My age is Suraj # Driver code
Arbitrary Keyword Arguments myFun(first='Geeks', mid='for',
last='Geeks')
In Python Arbitrary Keyword
Output:
Arguments, *args, and first == Geeks
**kwargs can pass a variable mid == for
number of arguments to a function last == Geeks
using special symbols. There are Docstring
two special symbols: The first string after the function is
 *args in Python (Non-Keyword
called the Document string
Arguments) or Docstring in short. This is used
 **kwargs in Python (Keyword
to describe the functionality of the
Arguments) function. The use of docstring in
Example 1: Variable length non- functions is optional but it is
keywords argument considered a good practice.
Python
The below syntax can be used to
# Python program to illustrate
# *args for variable number of print out the docstring of a function.
arguments Syntax:
def myFun(*argv): print(function_name.__doc__)
for arg in argv: Example: Adding Docstring to the
print(arg) function
Python
# A simple Python function to
myFun('Hello', 'Welcome', 'to', check
'GeeksforGeeks') # whether x is even or odd
Output:
Hello
Welcome def evenOdd(x):
to """Function to check if the
GeeksforGeeks number is even or odd"""
Example 2: Variable length
if (x % 2 == 0):
keyword arguments print("even")
Python
else:
# Python program to illustrate print("odd")
# *kwargs for variable number of
keyword arguments
# Driver code to call the function
print(evenOdd.__doc__)
def myFun(**kwargs):
for key, value in
Output:
kwargs.items():
Function to check if the
print("%s == %s" % (key, number is even or odd
value))
Python Function within cube_v2 = lambda x : x*x*x

Functions print(cube(7))
A function that is defined inside print(cube_v2(7))
another function is known as Output:
the inner function or nested 343
343
function. Nested functions can
access variables of the enclosing Recursive Functions in
scope. Inner functions are used so Python
that they can be protected from Recursion in Python refers to
everything happening outside the when a function calls itself. There
function. are many instances when you have
Python
to build a recursive function to
# Python program to
# demonstrate accessing of
solve Mathematical and
# variables of nested functions Recursive Problems.
Using a recursive function should
def f1(): be done with caution, as a
s = 'I love GeeksforGeeks' recursive function can become like
a non-terminating loop. It is better
def f2():
print(s)
to check your exit statement while
creating a recursive function.
f2() Python
def factorial(n):
# Driver's code if n == 0:
f1() return 1
Output: else:
return n * factorial(n -
I love GeeksforGeeks
1)
Anonymous Functions
in Python print(factorial(4))
Output
In Python, an anonymous
24
function means that a function is
Here we have created a recursive
without a name. As we already
function to calculate the factorial of
know the def keyword is used to
the number. You can see the end
define the normal functions and the
statement for this function is when
lambda keyword is used to create
n is equal to 0.
anonymous functions.
Python Return Statement in
# Python code to illustrate the Python Function
cube of a number
# using lambda function
The function return statement is
def cube(x): return x*x*x used to exit from a function and go
back to the function caller and
return the specified value or data # Driver Code (Note that lst is
item to the caller. The syntax for modified
# after function call.
the return statement is: lst = [10, 11, 12, 13, 14, 15]
return [expression_list] myFun(lst)
The return statement can consist of print(lst)
a variable, an expression, or a Output:
constant which is returned at the [20, 11, 12, 13, 14, 15]
end of the function execution. If When we pass a reference and
none of the above is present with change the received reference to
the return statement a None object something else, the connection
is returned. between the passed and received
Example: Python Function Return parameters is broken. For
Statement example, consider the below
Python program as follows:
def square_value(num): Python
"""This function returns the def myFun(x):
square
value of the entered number""" # After below line link of x
return num**2 with previous
# object gets broken. A new
object is assigned
print(square_value(2)) # to x.
print(square_value(-4)) x = [20, 30, 40]
Output:
4
16 # Driver Code (Note that lst is
Pass by Reference and not modified
# after function call.
Pass by Value lst = [10, 11, 12, 13, 14, 15]
One important thing to note is, in myFun(lst)
print(lst)
Python every variable name is a
reference. When we pass a Output:
[10, 11, 12, 13, 14, 15]
variable to a function Python, a
Another example demonstrates
new reference to the object is
that the reference link is broken if
created. Parameter passing in
we assign a new value (inside the
Python is the same as reference
function).
passing in Java. Python
Python
def myFun(x):
# Here x is a new reference to
same list lst
# After below line link of x
def myFun(x):
with previous
x[0] = 20
# object gets broken. A new
object is assigned
# to x.
x = 20 What are the 4 types of Functions in
Python?
The main types of functions in
# Driver Code (Note that x is not
Python are:
modified
 Built-in function
# after function call.
x = 10  User-defined function
myFun(x)  Lambda functions
print(x)  Recursive functions
Output: How to Write a Function in
10
Python?
Exercise: Try to guess the output
of the following code. To write a function in Python you
Python can use the def keyword and then
def swap(x, y): write the function name. You can
temp = x provide the function code after
x = y using ‘:’. Basic syntax to define a
y = temp function is:
def function_name():
# Driver code
x = 2 #statement
y = 3 What are the parameters of a function in
swap(x, y) Python?
print(x) Parameters in Python are the
print(y) variables that take the values
Output: passed as arguments when calling
2 the functions. A function can have
3
any number of parameters. You
Quick Links
can also set default value to a
 Quiz on Python Functions
parameter in Python.
 Difference between Method and What is Python main function?
Function in Python The Python main function refers to
 First Class functions in Python the entry point of a Python
 Recent articles on Python program. It is often defined using
Functions. the if __name__ ==
FAQs- Python Functions "__main__": construct to ensure
What is function in Python? that certain code is only executed
Python function is a block of code, when the script is run directly, not
that runs only when it is called. It is when it is imported as a module.
programmed to return the specific
task. You can pass values in Three 90 Challenge is back on
functions called parameters. It popular demand! After
helps in performing repetitive tasks. processing refunds worth INR
1CR+, we are back with the
offer if you missed it the first
time. Get 90% course fee refund
in 90 days. Avail now!
Ready to dive into the
future? Mastering Generative AI
and ChatGPT is your gateway to
the cutting-edge world of AI.
Perfect for tech enthusiasts, this
course will teach you how to
leverage Generative
AI and ChatGPT with hands-on,
practical lessons. Transform your
skills and create innovative AI
applications that stand out. Don't
miss out on becoming an AI
expert – Enroll now and start
shaping the future!

You might also like