OOPS IN PYTHON – Part 1
CLASS, OBJECTS, CONSTRUCTORS(Methods)
Principles of object-oriented programming
Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Class
Template / blueprint that describes the data and behavior associated with the class
instantiation.
logical template to create the objects that share common properties and methods.
Group of objects which have common properties.
It is a logical entity that contains some attributes and methods.
Classes are created by keyword class.
Attributes are the variables that belong to a class.
Think of the class as a sketch (prototype) of a house. It contains all the details
about the floors, doors, windows, etc. Based on these descriptions we build the
house. House is the object.
Since many houses can be made from the same description, we can create many
objects from a class.
Pto…
Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute classDemo12.py
Syntax:
class ClassName:
<statement-1>
<statement-N>
The __init__() Function
All classes have a function called __init__()
__init__() executes when the class is initiated.
Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created:
Note:
The __init__() function is called automatically every time the class is being
used to create a new object.
classDemo2.py
Object
An entity that has state and behavior.
It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and
methods.
All functions have a built-in attribute __doc__, which returns the docstring
defined in the function source code.
When we define a class, it needs to create an object to allocate the memory.
Syntax to Create Object:
referencevariable = classname()
Example:
Example: s = Student()
classDemo1.py
Reference Variable
The variable which can be used to refer object is called reference variable.
By using reference variable, we can access properties and methods of object.
Quiz:
Write a Python program to create a Student class and Creates an object to it. Call
the method talk() and speak() to display student details
classDemo2.py
Self Variable:
self is the default variable which is always pointing to current object (like this
keyword in Java)
By using self we can access instance variables and instance methods of object.
Note:
self should be first parameter inside constructor
def __init__(self):
self should be first parameter inside instance methods
def talk(self):
Constructor Concept: constructorDemo1.py
Constructor is a special method in python.
The name of the constructor should be __init__(self)
Constructor will be executed automatically at the time of object creation.
The main purpose of constructor is to declare and initialize instance variables.
Per object constructor will be exeucted only once.
Constructor can take atleast one argument(atleast self)
Constructor is optional and if we are not providing any constructor then python will
provide default constructor.
def __init__(self,name,rollno,marks):
self.name = 'Tarus'
self.age = 40
self.marks = 80
classMethod1.py
Methods Constructors
Name of method can be any name. Constructor name should be always
__init__
Method will be executed if we call Constructor will be executed
that method. automatically at the time of object
creation.
Per object, method can be called any Per object, Constructor will be
number of times executed only once.
Inside method we can write business Inside Constructor we have to declare
logic and initialize instance variables.
Types of Variables:
3 types of variables allowed in a Python class.
1. Instance Variables (Object Level Variables)
2. Static Variables (Class Level Variables)
3. Local variables (Method Level Variables)
1. Instance variables:
Instance variables:
Variables within a class but outside any method.
Initialized when the class is instantiated.
Can be accessed from inside any method, constructor or blocks of that
particular class.
Value of a variable is varied from object to object
For every object a separate copy of instance variables will be created.
Where we can declare Instance Variables:
i. Inside Constructor by using self variable
ii. Inside Instance Method by using self variable
iii. Outside of the class by using object reference variable
i. Inside Constructor by using self variable
Use self keyword to declare instance variables. Once objects are created,
automatically these variables will be added to the object. selfCons.py
ii. Inside Instance Method by using Self Variable:
We can also declare instance variables inside instance method by using self
variable. If any instance variable declared inside instance method, that
instance variable will be added once we call that method. selfCons2.py
iii. Outside of the class by using object reference variable
add instance variables outside of a class to a particular object.
selfCons3.py
How to Access Instance Variables:
Access instance variables within the class by using self variable and outside of the class
by using object reference.
accessInstanceVar.py
How to delete Instance Variable from the Object:
Within a class we can delete instance variable as follows
del self.variableName
From outside of class we can delete instance variables as follows
del objectreference.variableName
variableDelete.py
2. Static Variables:
Variables declared within a class, outside any method, with the static keyword.
Variable can be shared by all class instances For total class only one copy of
static variable will be created and shared by all objects of that class.
Static variables be accessed either by class name or by object reference. But
recommended to use class name.
Nb: Instance Variable vs Static Variable:
In the case of instance variables for every object a separate copy will be
created, but in the case of static variables for total class only one copy will be
created and shared by every object of that class.
• instanceStaticVar.py
Various Places to declare Static Variables:
In general declare static var within the class directly but from out side of any method
Inside constructor by using class name
Inside instance method by using class name
Inside class method by using either class name or class variable
Inside static method by using class name : staticVariable2.py
How to access Static Variables:
inside constructor: by using either self or classname
inside instance method: by using either self or classname
inside class method: by using either cls variable or classname
inside static method: by using classname
From outside of class: by using either object reference or classname accessStaticVar.py
How to Delete Static Variables of a Class:
Delete static variables from anywhere by using the following syntax
del classname.variablename
But inside classmethod we can also use cls variable
del cls.variablename
deleteStaticVar.py
3. Local Variables:
Variables defined inside methods, constructors or blocks.
Declared and initialized within the method and the variable will be destroyed
when the method has completed.
Local variables will be created at the time of method execution and destroyed
once method completes.
Local variables of a method cannot be accessed from outside of method.
localVariable.py
Types of Methods:
1. Instance Methods
2. Class Methods
3. Static Methods
Instance Methods:
Methods defined/declared inside the class.
Inside instance method declaration, we have to pass self variable. def m1(self):
By using self variable inside method we can able to access instance variables.
Within the class we can call instance method by using self variable and from
outside of the class we can call by using object reference.
instanceMethods.py
Setter and Getter Methods:
• Set and get the values of instance variables by using getter and setter methods.
Setter Method:
setter methods can be used to set values to the instance variables. setter
methods also known as mutator methods.
Syntax:
def setVariable(self,variable):
self.variable=variable
Example:
def setName(self,name):
self.name=name
Getter Method:
Getter methods can be used to get values of the instance variables. Getter
methods also known as accessor methods.
Syntax:
def getVariable(self):
return self.variable
Example:
def getName(self):
return self.name
setterGetterMethod.py
Class Methods:
Inside method implementation if we are using only class variables (static
variables), then such type of methods we should declare as class method.
We can declare class method explicitly by using @classmethod decorator.
For class method we should provide cls variable at the time of declaration
We can call classmethod by using classname or object reference variable.
classMethods.py (check)
countObjects.py
Static Methods:
In general these methods are general utility methods.
Inside these methods we won't use any instance or class variables
Here we won't provide self or cls arguments at the time of declaration.
We can declare static method explicitly by using @staticmethod decorator
We can access static methods by using classname or object reference
staticMethod.py
Nb:
In general we can use only instance and static methods. Inside static method we
can access class level variables by using class name.
Class methods are most rarely used methods in python.
Passing Members of One Class to Another Class:
Members of one class can be accessed from inside another class.
multipleClasses.py
Inner Classes
Declaring a class inside another class. Consider:
class Car:
.....
class Engine:
......
Expln: Without existing Car object there is no chance of existing Engine object. Hence
Engine class should be part of Car class.
class University:
.....
class Department:
......
Expln:
Without existing university object there is no chance of existing Department
object
Pto…
class Human:
.....
class Head:
.....
Expln:
Without existing Human there is no chance of existing Head. Hence Head
should be part of Human.
innerClass1.py
innerClass2.py
innerClass3.py
Destructors: destructor1.py, destructor2.py
Destructor is a special method and the name should be __del__
Just before destroying an object Garbage Collector always calls destructor to
perform clean up activities (Resource deallocation activities like close database
connection etc).
Once destructor execution completed, then Garbage Collector automatically
destroys that object.
Note: The job of destructor is not to destroy object but it is just to perform clean
up activities