ObjectAndClass PDF
ObjectAndClass PDF
Real-world objects share two characteristics. They all have state and
behaviour.
The dynamic memory allocated at run time for the members [non-static
variables] of the class is known as object.
The data present inside object of a class at that point of time is known as
state of the object.
Behaviour:
Syntax:
class className:
''' documenttation string '''
variables:instance variables,static and local variables
methods: instance methods,static methods,class methods
print(classname. __doc__)
help(classname)
referencevariable = classname()
Example: -
p = Person ()
Suppose there is a class named Customer, then see how to create its
object.
c=Customer ()
class Car:
# class attribute
Type1 = "Four wheeler"
# instance attribute
def __init__(self, name, old):
self.name = name
self.old = old
There are a few things to note when looking at the above example.
The class is made up of attributes (data) and methods (functions)
Attributes and methods are simply defined as normal variables and functions
Attributes that apply to the whole class are defined first, and are called class
attributes.
Attributes that apply to a specific instance of a class (an object) are called
instance attributes. They are generally defined inside __init__(); this is not
necessary, but it is recommended (since attributes defined outside of __init__()
run the risk of being accessed before they are defined).
# class attribute
Type1 = "Four wheeler"
def read(self):
self.name="Maruti"
def show(self):
print(self.name)
print(__class__.Type1)
Self-variable In Python:
self is the default variable which is always pointing to current object (like
this keyword in Java)
Usage of self-variable
Every method, included in the class definition passes the object in question
as its first parameter. The word self is used for this parameter (usage of self
is actually by convention, as the word self has no inherent
To differentiate between formal parameter and data member of the class, the data
members of the class must be preceded by "self".
Syntax-:
class Employee:
def __init__(self,id,name):
self.id=id
self.name=name
def display(self):
print(self.id)
print(self.name)
e=Employee(101,'Scott')
e.display()
Constructor in Python
Whenever a class is instantiated __new__ and __init__ methods are
called. __new__ method will be called when an object is created and
__init__ method will be called to initialize the object.
cls parameter
The first parameter cls represents the class being created.
In the base class object, the __new__ method is defined as a static method
which requires to pass a parameter cls. cls represents the class that is
needed to be instantiated, and the compiler automatically provides this
parameter at the time of instantiation.
Constructors are executed as part of the object creation.
Purpose Of Constructor
The purpose of constructor is to initialize an object called object
initialization. Constructors are mainly created for initializing the object.
Initialization is a process of assigning user defined values at the time of
allocation of memory space.
class Test:
def __init__(self):
print(" Class Test Constructor exeuction...")
Output:
Class Test Constructor exeuction...
Class Test Constructor exeuction...
Class Test Constructor exeuction...
class Person:
def __init__(self,name,age,sex,weight,height):
self.name=name
self.age=age
self.sex=sex
self.weight=weight
self.height=height
def eating(self,msg):
print(msg)
def displayPersonInfo(self):
print("Name: ",self.name)
print("Age: ",self.age)
print("Sex: ",self.sex)
print("Weight: ",self.weight)
print("Height: ",self.height)
mark=Person("Mark",45,"Male",30,4.5)
mark.displayPersonInfo()
mark.eating("Can eat only Non-Veg Food")
print("===================================")
sachin=Person("Sachin",55,"Male",70,5.5)
sachin.displayPersonInfo()
sachin.eating("Can eat only Veg Food")
Default constructor
class Test:
def m1(self):
print('Hello')
t1.m1()
In this example, we do not have a constructor but still we are able to
create an object for the class. This is because there is a default
constructor implicitly injected by python during program compilation,
this is an empty default constructor that looks like this:
def __init__(self)
# no body, does nothing.
class Test:
def __init__(self,n1,n2):
self.a=n1
self.b=n2
def display(self):
print("a= ",self.a)
print("b= ",self.b)
t1=Test(10,20)
t1.display()
t2=Test(30,40)
t2.display()
No Constructor Overloading in Python
If you give it more than one constructor, that does not lead to constructor.
If you define the more than one same kind of constructor, then it will be
considered the last constructor and ignore the earlier constructor.
class Test:
def __init__(self):
print("First constructor")
def __init__(self):
print("Second constructor")
def __init__(self):
print("Third constructor")
t1=Test()
Output:
Third constructor
Two Different Kinds of Constructors in Python
class Test:
def __init__(self):
print("First constructor")
def __init__(self,a):
print("Second constructor")
self.a=a
class Test:
def __init__(self):
print("First constructor")
def __init__(self,a):
print("Second constructor")
self.a=a
class Test:
def __init__(self,a=10,b=20):
print("constructor calling...")
self.a=a
self.b=b
print("a= ",self.a,"b=",self.b)
# creating object of the class
t1=Test()
t2=Test(40)
t3=Test(50,60)
Output:
constructor calling...
a= 10 b= 20
constructor calling...
a= 40 b= 20
constructor calling...
a= 50 b= 60
Method Constructor
1 Method can be any user defined name Constructor name should be always
__init__
2 Method should have return type It should not have any return type
(even void)
3 Method should be called explicitly It will be called automatically
either with object reference or class whenever object is created
reference
4 Inside Method we can write business Inside Constructor we have to declare
logic and initialize instance variables
Types of Variables:
1. Instance Variables:
If the value of a variable is varied from object to object, then such type of
variables is called instance variables.
class Student:
def __init__(self):
self.name="Scott"
self.rollno=101
self.age=20
s1=Student()
print(s1.__dict__)
Output:
{'name': 'Scott', 'rollno': 101, 'age': 20}
Example:
class Demo:
def __init__(self):
self.a=10
self.b=20
def f1(self):
self.c=30
class Demo:
def __init__(self):
self.a=10
self.b=20
def f1(self):
self.c=30
OutPut:
{'a': 10, 'b': 20}
{'a': 10, 'b': 20, 'c': 30}
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
How We can access Instance variables With-in Class and Outside the
class:
We can access instance variables with in the class by using self-variable and
outside of the class by using object reference.
class Demo:
def __init__(self):
self.a=10
self.b=20
# With-in Class We can access instance variable by Using self variable
def info(self):
print("a= ",self.a)
print("b= ",self.b)
How We can delete Instance variables With-in Class and Outside the
class:
Output:
{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
{'b': 20, 'c': 30, 'd': 40, 'e': 50}
class Demo:
def __init__(self):
self.a=10
self.b=20
self.c=30
self.d=40
self.e=50
class Demo:
def __init__(self):
self.a=10
self.b=20
self.c=30
self.d=40
self.e=50
d2=Demo()
print(d1.__dict__)
print(d2.__dict__)
print("========================================")
del d1.a
print(d1.__dict__)
print(d2.__dict__)
Output:
{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
===============================================
{'b': 20, 'c': 30, 'd': 40, 'e': 50}
{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
Note:-
For instance, variable a separate copy will be maintained for every
object. if we are change the value of instance variables of one
object then those change will not be reflected to the remaining
object of that class.
class Demo:
def __init__(self):
self.a=10
self.b=20
d2=Demo()
print("For d2=> ",d2.a,d2.b)
print("===================================")
print("After changing d1 => ",d1.a,d1.b)
print("For d2=> ",d2.a,d2.b)
Output
Before changing d1 => 10 20
For d2=> 10 20
===================================
After changing d1 => 30 40
For d2=> 10 20
Static variable In Python
Static variable is used for fulfil the common requirement. For Example,
company name of employees, college name of students etc. Name of the
college is common for all students.
When we create a static variable as a company name then only once memory
is allocated otherwise it allocate a memory space each time for every
employee.
Static variable
If the value of a variable is not varied from object to object then it is never
recommended to declare that variable at object Level, we have to declare
such type variable of variables at class level.
In the case of instance variable for every object a separate copy will be
created. But In the case of static variable only one copy will be created at
class level and share that copy for every object of the class.
static variable will be created at the time of class Loading & destroy at the
time of class unloading. Hence the scope of the static variable is exactly
same as the scope of the class
Note-
If the value of a variable is varied from object to object then we should go
for instance variable. In the case of instance variable for every object a
separate copy will be created.
If the value of a variable is same from all object then we should go for
static variable. In the case of static variable only one copy will be created
at class level and share that copy for every object of the class.
Where and how we can declare variable as static variable with-in class
.
Static variables we can declare with in the class directly but outside of any
method or block or constructor.
class Student:
college_name='IIT'
def __init__(self,rollno,name):
self.rollno=rollno
self.name=name
class Student:
def __init__(self,rollno,name):
self.rollno=rollno
self.name=name
@classmethod
def m1(cls):
cls.college_name='ITM'
Student.college_name='ITM'
Static variables we can declare also Inside static method by using class
name
class Student:
def __init__(self,roll_no,name):
self.roll_no=roll_no
self.name=name
@staticmethod
def m1(self):
Student.college_Name="ITM"
def __init__(self):
#acessing static variable using self inside constructor
print(self.college_Name)
class Student:
college_Name="ITM"
def m1(self):
#acessing static variable using self inside Instance Method
print(self.college_Name)
We can access static variable inside class method: by using either cls
variable or classname
class Student:
college_Name="ITM"
@classmethod
def m1(cls):
#acessing static variable using cls inside class Method
print(cls.college_Name)
class Student:
college_Name="ITM"
@staticmethod
def m1():
If you have created both the instance and static variables with the same
name, then if the variable is accessed from the reference variable outside the
class, then the instance variable will be accessible, in this case static will not
be accessible using reference variable. then we can access static variable
outside the class by using class name.
def __init__(self):
Student.college_Name="IIT"
@staticmethod
def m1():
Student.college_Name="IIT"
s1.m1()
print("After modifying static variable through static Method")
class Student:
college_Name="ITM"
@classmethod
def m1(cls):
cls.college_Name="IIT"
s1.m1()
print("After modifying static variable through class Method")
When we are trying to modify static variable value by using object reference
or self then the value of static variable won't be changes, just a new instance
variable with that name will be added to that particular object.
class Student:
college_Name="ITM"
def m1(self):
self.college_Name="IIT"
Output
ITM
IIT
Program
Let us say we want to assign a unique number to each product object. The
first product object should be given a number 100 and subsequent product
objects should have that value increased by 1. We can accomplish this by
using a combination of static and instance variables as shown below:
class Product:
productId=100
def __init__(self,name,price,brand):
self.name=name
self.price=price
self.brand=brand
Product.productId +=1
def displayPrdouctDetails(self):
print("ProductId:",Product.productId)
print("ProductName:",self.name)
print("ProductPrice:",self.price)
print("ProductBrand:",self.brand)
prod1=Product('Ipad',10000,'Apple')
prod1.displayPrdouctDetails()
print("============================")
prod2=Product('Redmi4A',10000,'Redmi')
prod2.displayPrdouctDetails()
Output
ProductId: 101
ProductName: Ipad
ProductPrice: 10000
ProductBrand: Apple
============================
ProductId: 102
ProductName: Redmi4A
ProductPrice: 10000
ProductBrand: Redmi
The Variables which are defined inside a method or any block is known as local
variable.
The scope of the local variable is only within the method, it means that the local
variable can only be accessed inside the method, outside the method cannot be
accessed the local variable.
There are three types of methods in Python:
1. Instance Methods.
2. Class Methods
3. Static Methods
Instance Methods.
Inside method implementation if we are using instance variables then such
type of methods is called instance methods.
This method can only be called if the class has been instantiated.
Once an object of that class has been created the instance method can be
called and can access all the attributes of that class through the reserved
word self.
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return (self.a + self.b)
def sub(self):
return (self.a - self.b)
def mul(self):
return (self.a * self.b)
def div(self):
return (self.a /self.b)
c1 = Calculator(10, 20)
print("Addition= ",c1.add())
print("Substraction= ",c1.sub())
print("Multiplication= ",c1.mul())
print("Division= ",c1.div())
In the above program, a and b are instance variables and these get initialized
when we create an object for the Calculator class. If we want to call
add(),sub(),mul(),div() function which is an instance method, we must create
an object for the class.
#create an Object
p1=Person()
p1.setName('john')
p1.setAge(101)
print("Name= ",p1.getName())
print("Age= ",p1.getAge())
Class Method
Inside method implementation if we are using only class variables (static
variables), then such type of methods we should declare as class method.
Class Variable: A class variable is nothing but a variable that is defined
outside the constructor. A class variable is also called as a static variable.
A class method is a method which is bound to the class and not the object of
the class.
Class Method takes a class parameter that points to the class and not the
object instance. As we are working with ClassMethod we use the cls
keyword.
Class method can be called without having an instance of the class.
Car.run('Maruti')
Car.run('Ford')
Program to track the number of objects created for a class:
class Demo:
count=0
def __init__(self):
Demo.count=Demo.count+1
@classmethod
def noOfObjects(cls):
print('The number of objects created for Demo class:',cls.count)
#create an object
d1=Demo()
d2=Demo()
Demo.noOfObjects()
d3=Demo()
d4=Demo()
d5=Demo()
Demo.noOfObjects()
Static Methods
In general, these methods are general utility methods.
A static method is also a method which is bound to the class and not the
object of the class.
Inside these methods we won't use any instance or class variables. They are
utility type methods that take some parameters and work upon those
parameters.
A static method does not receive an implicit first argument such as instance
method receive an implicit first argument as a self-variable and class method
receive an implicit first argument as a cls variable..
Syntax:
How to define a class method and a static method?
to define a static method we use @staticmethod decorator.
class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function fun.
A static method can’t access or modify class state.
It is present in a class because it makes sense for the method to be present in class.
You could use a static method when you have a class but you do not need an
specific instance in order to access that method. For example if you have a class
called Math and you have a method called factorial (calculates the factorial of a
number). You probably won’t need an specific instance to call that method so you
could use a static method.
class Math:
@staticmethod
def factorial(number):
if number == 0:
return 1
else:
return number * MethodTypes.factorial(number - 1)
factorial = MethodTypes.factorial(5)
print(factorial)