Python
is an object oriented programming language.- Every real world entity is an
object
, almost everything in Python is anobject
- OOP allows us to write code that is
repeatable
,well organized
andmemory efficient
e.g. x = 5
# We want to store a data i.e. 5, 5 is stored in a computer memory at a particular hexadecimal memory address.
# Remembering the hexadecimal memory address will be very complicated for the developer to manage data.
# We will access the memory address to store and retrieve data, so we map the address with a meaningful variable name.
# We create an integer object with value = 5 and assign its memory address to a variable x.
# Data type, value, reference count and other informations are associated with object, variable just holds the memory address.
str()
,int()
... are the constructor functions.
# string
print(type("a string"))
# integer
print(type(5))
# float
print(type(5.0))
# list
print(type([1, 2, 3]))
# tuple
print(type((1, 2, 3)))
# set
print(type({1, 2, 3}))
# dictionary
print(type({1 : "Kirankumar", 2 : 25, 3 : "Data Scientist"}))
-------------------------------------------------------------
Output :
-------------------------------------------------------------
<class 'str'>
<class 'int'>
<class 'float'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
# Constructor Functions
int(2.5) = 2
str(5) = "5"
float(7) = 7.0
Blueprint
|Template
forreal world entities
and creatingobjects
- Defines
Attributes
|Properties
|Variables
andBehavior
|Action
| MemberFunction
orMethods
Every class has three essential components:
Identity
: Unique name to identify the object ( class Person )Property
: Attributes | Data ( About the object: Name, Gender, Age, Height, Weight )Method
: Behaviour | Action | Operation ( What the object can do? Read, Write, Walk, Run, Study, Teach )
class Employee(object):
pass
# Person is a class name
class Person:
# Special Method or Constructor Method | class Person has two properties name and age.
def __init__(self, name, age):
self.name = name
self.age = age
# class Person has method introduce.
def introduce(self):
print(f"Hi, my name is {self.name} and I'm {self.age} years old.")
- Calling a
class
to create anobject
# Class is called with paranthesis.
Employee()
Instance
of class, that can store value (information)- e.g. If Smartphone is a Class then Apple, Samsung, Motorola, Oneplus are instances.
# emp1 is an object name and Employee is the class name.
emp1 = Employee()
- Automatically the method is called whenever an
object
is created. Default Constructor
: Constructor withno
parameters | arguments
def __init__(self, name, age):
self.name = name
self.age = age
Special Constructor
orConstructor Method
orSpecial Method
orMagic Method
orInit Method
Attributes
are initialized in__init__()
- Defined automatically when we create any class object, and automatically invokes whenever an object is created.
__init__()
function is executed automatically with every new class instance.- The arguments or parameters passed with
__init__()
are calledinstance attributes
- First parameter will always be a variable
self
- Process of creating an
object
( Instance of a class ) is calledinstantiation
- Every new object
instance
is located at a different memory address. - The process to create an
object
is similar to afunction call
( ObjectName = ClassName() )
# Define Function:
def function_name(argument1, argument2):
pass
# Call Function:
function_name(parameter1 = value1, parameter2 = value2)
def greet(name):
print(f'Good Morning {name}')
print(greet(name='Kirankumar'))
# Output:
Good Morning Kirankumar
None
None
: When a function doesn't return anything, we get None.
def greet(name):
return f'Good Morning {name}'
print(greet(name='Kirankumar'))
# Output:
Good Morning Kirankumar
def example(arg_1, arg_2, *args, **kwargs):
Function
defined inside body of aclass
- Defines
action
orbehaviour
of an object.
def introduce(self):
print(f"Hi, my name is {self.name} and I'm {self.age} years old.")
- A reference to the current
instance
( attributes and methods ) of the class. - Used to access or reference
attributes
andmethods
of class. self
provides a flexibility to call theinstance attributes
in any method defined inside the class irrespective of it's scope.
class Employee(object):
def __init__(self, name, age, email, designation)
self.name = name
self.age = age
self.email = email
self.designation = designation
instance attributes : name, age, email, designation
object will be created with initial values passed to the instance attributes
Functions
that belongs to an object are calledmethods
or Simplyfunctions
defined insideclass
aremethods
name = 'Kirankumar' # String object "name" is created.
name.upper() # upper() is the method of string object.
Abstraction
Polymorphism
Inheritance
Encapsulation
Show
only important information andhide
internal implementation details from users.- e.g. Mobile can do many things like make a call, take pictures, play games, watch movies, etc.
- It doesn't show the inside process of how its doing the things (Implementation parts are hidden)
- Having more than one form.
- In Python we can use the same function on different data types or different sequence or collections.
- Allow to call methods of base class in derived class.
- e.g A person at same time is a father, a husband, an employee and behaves accordingly.
- Same
method
name but differentattributes
or number of parameters.
# Same function can be used to count the characters in a string as well as number of items in a list
len("Kirankumar") : 10
len([1, 2, 3, 4, 5]) : 5
Parent | Base | Super
ClassChild | Derived | Sub
ClassInherit
theattributes
( properties ) andmethods
( behaviour ) from base class to a new derived class.Inheritance
enables us tocreate
a newclass
from existing class by adding new functionality to it or simply modifying it.- The pre existing class is known as a
Base Class
and the newly defined class is known as aDerived Class
- To inherit
__init__()
method of theparent class
inside derived class, usesuper().__init__()
- A
class
can bederived
from more than onebase class
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
- Inherit from
derived class
- Features of
base class
andderived class
are inherited into anew derived class
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
- When the
__init__()
method is defined insidederived
class, itoverrides
thebase
class
class Base:
pass
class Derived(Base):
pass
_x
:protected
attribute and method |Single
underscore | Can be accessed usinginstance
__x
:private
attribute and method |Double
underscore | Cannot be accessed usinginstance
Bind
together thedata
,attributes
andmethods
( Class = Data + Properties + Behaviour )Restrict
access to methods, attributes and variables of Class.Prevents
data from directmodification
- e.g. A company has several departments Production, HR, Accounts, Marketing.
- All these departments makes up a company, and each department has it's own purpose and actions.
- We denote
private attribute
using single underscore_
and aprotected attribute
using double underscore__
Getter
/Setter
- Pythonic way to
set
andget
protected attributes.
- Decorator modify or extend the behaviour of a
Function
orClass
without permanently modifying it.
- Functions are
First Class Objects
: Can be used or passed asarguments
- Function is an
instance
ofObject type
- Function can be stored in a
variable
- Function can be created inside a function
- Function can be passed as a
parameter
to another function - Function can be returned as a result from another function
def uppercase(text):
return text.upper()
capital = uppercase # Storing function in a variable
print(capital('Hello'))
-----------------------
Output :
-----------------------
HELLO
-----------------------
def adder(x):
def add(y): # Creating a function inside function
return x + y
return adder # Returning function as a result
add15 = adder(15)
print(add15(10))
-----------------------
Output :
-----------------------
25
- Define a
class
- Instantiate an
object
aclass
- Use
attributes
andmethods
to define theproperties
andbehaviors
of an object. - Use
inheritance
to createchild classes
from aparent class
- Reference a method in a
parent class
usingsuper()
- Check if an
object
inherits from another class usingisinstance()
- Makes Program easy to understand.
- Class is sharable, code can be reused.
- Data is safe and secure with data abstraction.
- Same operator behaves differently with different
data types
according to context. - (+) Operator will perform arithmetic addition on two numbers, merge two lists and concatenate two strings.
- But it does not performs same operations on user defined class
- we need to implement __add__() function in the class.
- Python manages its memory using private
heap space
Objects
are stored inheap
( Inaccessible to the programmers )- In built
garbage collector
torecycle
the unused memory for theprivate heap space
Terminates
theloop
and control flows to the statement after the body of loop.
Terminates
current iteration of the statement,skips
the rest of the code in current iteration- Control flows to the next iteration of the Loop.
- Empty statement just used to bypass the error situation.
- Functions that returns an
iterable collection
of items on which we can apply loop or control flow.
- Display
documentation
ofmodules
,classes
,functions
andkeywords
- List of valid
attributes
andmethods
of an object based on its datatype and state.
Operator | Expression | Special Function |
---|---|---|
Addition | p1 + p2 | p1.__add__(p2) |
Subtraction | p1 - p2 | p1.__sub__(p2) |
Multiplication | p1 * p2 | p1.__mul__(p2) |
Power | p1 ** p2 | p1.__pow__(p2) |
Division | p1 / p2 | p1.__truediv__(p2) |
Floor Division | p1 // p2 | p1.__floordiv__(p2) |
Remainder (modulo) | p1 % p2 | p1.__mod__(p2) |
Bitwise Left Shift | p1 << p2 | p1.__lshift__(p2) |
Bitwise Right Shift | p1 >> p2 | p1.__rshift__(p2) |
Bitwise AND | p1 & p2 | p1.__and__(p2) |
Bitwise OR | p1 | p2 | p1.__or__(p2) |
Bitwise XOR | p1 ^ p2 | p1.__xor__(p2) |
Bitwise NOT | ~p1 | p1.__invert__() |
Operator | Expression | Special Functions |
---|---|---|
Less than | p1 < p2 | p1.__lt__(p2) |
Less than or equal to | p1 <= p2 | p1.__le__(p2) |
Equal to | p1 == p2 | p1.__eq__(p2) |
Not equal to | p1 != p2 | p1.__ne__(p2) |
Greater than | p1 > p2 | p1.__gt__(p2) |
Greater than or equal to | p1 >= p2 | p1.__ge__(p2) |