Python OOPs Concepts
Python OOPs Concepts
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!