Lecture8 Py
Lecture8 Py
ge
To map with real world scenarios, we started using objects in code.
olle
This is called object oriented programming.
na C
Ap
Class & Object in Python
ge
Class is a blueprint for creating objects.
olle
C
#creating class
na
class Student:
Ap
name = “karan kumar”
s1 = Student( )
print( s1.name )
Class & Instance Attributes
lege
ol
Class.attr
C
obj.attr
pna
A
_ _init_ _ Function
Constructor
All classes have a function called __init__(), which is always executed when the object is being
initiated.
#creating object
e
#creating class
leg
class Student:
l
s1 = Student( “karan” )
Co
def __init__( self, fullname ): print( s1.name )
na
self.name = fullname
Ap
*The self parameter is a reference to the current
instance of the class, and is used to access variables
that belongs to the class.
Methods
Methods are functions that belong to objects.
ge
def __init__( self, fullname ): s1.hello( )
lle
self.name = fullname
a Co
n
def hello( self ):
Ap
print( “hello”, self.name)
Let‘s Practice
e
Create student class that takes name & marks of 3 subjects as arguments in constructor.
lleg
Then create a method to print the average.
a Co
Apn
Static Methods
Methods that don’t use the self parameter (work at class level)
class Student:
@staticmethod #decorator
e
def college( ):
lleg
print( “ABC College” )
a Co
Apn
*Decorators allow us to wrap another function in order to
extend the behaviour of the wrapped function, without
permanently modifying it
Important
ge
Abstraction
olle
Hiding the implementation details of a class and only showing the essential features to the user.
na C
Encapsulation
Ap
Wrapping data and functions into a single unit (object).
Let‘s Practice
e
Create Account class with 2 attributes - balance & account no.
lleg
Create methods for debit, credit & printing the balance.
a Co
Apn