Python Recap - 4 OOP
Python Recap - 4 OOP
2
TCS Internal
Python Objects
Contents
In OOP, a program is seen as comprising of a collection of
objects, that act on each other.
3
Python Classes
Contents
object that is instantiated from this class.
4
Python - Attributes and methods
Objects can store data using ordinary variables that belong to the object.
Contents
Collectively, the fields and methods can be referred to as the attributes
of that class.
Fields are of two types - they can belong to each instance/object of the
class or they can belong to the class itself.
5
Basic Syntax
Example
6
The self keyword
The self keyword represents the instance of a class
By using the "self" keyword we can access the attributes and methods of
the class in python.
Whenever an instance method is declared, the first parameter passed to
the method is the self keyword. This represents the object which calls the
method.
Self is a convention and not a real python keyword – any other word can
be used other that self.
7
The __init__() method
The init method is a reserved method in python which is used to
initialize an object
When an object of a class is created/instantiated, the init method is
invoked automatically.
It is almost similar to a constructor as per OOP concepts
Filename : person.py
Output
8
Python – Class & object variable
As discussed earlier, there are two types of data fields- class variables and object
variables
Class variables are shared - they can be accessed by all instances of that
class. There is only one copy of the class variable and when any one object
makes a change to a class variable, that change will be seen by all the other
instances.
There are two other functionalities, one to remove and employee and
another to receive a greeting from any employee. Both these methods are
object variables i.e. they will be called by an instance of that class.
9
Example
The implementation :
10
Example – Contd..
Contd ..
11
Output
12
13