Overloading@python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

PYTHON

Nested Class or Inner Class:


Inner class is the concept of grouping of two or more classes. For example, Every Car needs an Engine,
but, Engine won't be used without a Car. Here user can have two classes Car and Engine and can make
the Engine an inner class to the outer class Car. This concept of nested classes helps saving code and
hide the code of Nested classes from the outside world. User can access the inner class in the outer
class using the self keyword. User can create an instance of the inner class and perform operations.
However, user can not access the outer class in an inner class.
• One way:
Example:
class Outer:
"""Outer Class"""
def __init__(self):
## instantiating the 'Inner' class
self.inner = self.Inner()
def reveal(self):
## calling the 'Inner' class function display
self.inner.inner_display("Calling Inner class function from Outer class")
class Inner:
"""Inner Class"""
def inner_display(self, msg):
print(msg)
• Second Way
User can make the instance of the Outer class and call it's reveal() method to execute the Inner class
method inner_display().
## creating an instance of the 'Outer' class
outer = Outer()
## calling the 'reveal()' method
outer.reveal()
• Third Way
Calling the Inner class method directly
Outer().Inner().inner_display("Calling the Inner class method directly")
• Fourth Way
User can create an instance of the inner class outside the outer class.
outer = Outer()
## instantiating the inner class
inner = outer.Inner() ## inner = Outer().Inner() or inner = outer.inner
inner.inner_display("Just Print It!")

• Multiple Inner Classes can be created where a class contains more than one inner class.
Example 1:
class Outer:
"""Outer Class"""
def __init__(self):
## Instantiating the 'Inner' class
self.inner = self.Inner()
## Instantiating the '_Inner' class
self._inner = self._Inner()
def show_classes(self):
print("This is Outer class")
1 SS
PYTHON

print(inner)
print(_inner)
class Inner:
"""First Inner Class"""
def inner_display(self, msg):
print("This is Inner class")
print(msg)
class _Inner:
"""Second Inner Class"""
def inner_display(self, msg):
print("This is _Inner class")
print(msg)
## ...

Example 2:
class Outer:
def __init__(self):
self.__x = 20
self.__str = "Outer Class"
def show(self):
self.i1 = self.Inner()
self.i1.display()
def fn(self):
print("Hello from fn() of Outer Class")
print("str : ", self.__str)
class Inner:
def __init__(self):
self.__str_in = "Inner Class"
self.outer=Outer()
def display(self):
print("str_in : ", self.__str_in)
print("Inside display() of Inner Class")
print("x : ", self.outer._Outer__x)
print("str : ", self.outer._Outer__str)
self.outer.fn()
obj = Outer()
obj.show()

• If variables are Public


class Outer:
def __init__(self):
self.x = 20
self.str = "Outer Class"
def show(self):
self.i1 = self.Inner()
self.i1.display()
def fn(self):
print("Hello from fn() of Outer Class")
print("str : ", self.str)
2 SS
PYTHON

class Inner:
def __init__(self):
self.__str_in = "Inner Class"
self.outer=Outer()
def display(self):
print("str_in : ", self.__str_in)
print("Inside display() of Inner Class")
print("x : ", self.outer.x)
print("str : ", self.outer.str)
self.outer.fn()
obj = Outer()
obj.show()

Overloading
Overloading, in the context of programming, refers to the ability of a function or an operator to
behave in different ways depending on the parameters that are passed to the function, or the
operands that the operator acts on. The same built-in operator or function shows different behaviour
for objects of different classes.

1. Operator Overloading
Consider that we have two objects which are a physical representation of a class (user-defined data
type) and we have to add two objects with binary ‘+’ operator it throws an error, because compiler
don’t know how to add two objects. So we define a method for an operator and that process is called
operator overloading. This special method automatically invoked when it is associated with that
particular operator. Operator Overloading means giving extended meaning beyond their predefined
operational meaning. For example, when we use + operator, the magic method __add__ is
automatically invoked in which the operation for + operator is defined whether to add two integers or
join two strings and merge two lists. There by changing this magic method’s code, we can give extra
meaning to the + operator.

# Python program to show use of


# + operator for different purposes.
print(1 + 2)
# concatenate two strings
print("Python"+"Program")
# Product two numbers
print(3 * 4)
# Repeat the String
print("Python"*4)
Output:
3
PythonProgram
12
PythonPythonPythonPython

Example 1:
# Python Program illustrate how to overload an binary + operator
class A:
3 SS
PYTHON

def __init__(self, a):


self.a = a
# adding two objects
def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
Output :
3
GeeksFor

Example 2:
# Python program to overload a comparison operators
class A:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
Output :
ob2 is greater than ob1

Example 3:
# Python program to overload equality and less than operators
class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is less than ob2"
else:
return "ob2 is less than ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"
4 SS
PYTHON

ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)
ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)
Output :
ob1 is less than ob2
Not equal

Python magic methods or special functions for operator overloading

OPERATOR MAGIC METHOD


Arithmetic Operators:
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
Comparison Operators :
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
== __eq__(self, other)
!= __ne__(self, other)
Assignment Operators :
-= __isub__(self, other)
+= __iadd__(self, other)
*= __imul__(self, other)
/= __idiv__(self, other)
//= __ifloordiv__(self, other)
%= __imod__(self, other)
**= __ipow__(self, other)
2. Function Overloading
Function overloading is the ability to have multiple functions with the same name but with different
signatures. For instance, instead of writing multiple
methods that differ only slightly, we can write one
method and overload it. When an overloaded
function is called, the runtime first evaluates the
arguments/parameters passed to the function call
and judging by this invokes the corresponding
implementation. So, Depending on how the function
has been defined, we can call it with zero, one, two, or
even many parameters. This is referred to as "function
overloading".
5 SS
PYTHON

Example:
int area(int length, int breadth) {
return length * breadth;
}
float area(int radius) {
return 3.14 * radius * radius;
}
To overload a user-defined function in Python, we need to write the function logic in such a way that
depending upon the parameters passed, a different piece of code executes inside the function. Example:
class Student:
def hello(self, name=None):
if name is not None:
print('Hi ' + name)
else:
print('Hi ')
# Creating a class instance
std = Student()
# Call the method
std.hello()
# Call the method and pass a parameter
std.hello('Indian')
Output:
Hi
Hi Indian
The class Student has one function named hello(). The class takes the parameter name which has been
set to None. This means the method can be called with or without a parameter. We have created an
instance of the class which has been used to call the function twice, first with zero parameters and
secondly with one parameter.

6 SS

You might also like