100% found this document useful (1 vote)
119 views

ObjectAndClass PDF

Objects in object-oriented programming have state and behavior. An object is an instance of a class that is created dynamically in memory at runtime. The state of an object represents its data values, while its behavior represents the functions or methods that can be called on the object. Constructors in Python are used to initialize objects and are called automatically when a new object is created through the class. They allow values to be assigned to the new object's attributes.

Uploaded by

Ashutosh Trivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
119 views

ObjectAndClass PDF

Objects in object-oriented programming have state and behavior. An object is an instance of a class that is created dynamically in memory at runtime. The state of an object represents its data values, while its behavior represents the functions or methods that can be called on the object. Constructors in Python are used to initialize objects and are called automatically when a new object is created through the class. They allow values to be assigned to the new object's attributes.

Uploaded by

Ashutosh Trivedi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Object

 Objects are key to understanding object-oriented technology. Look around


right now and you will find many examples of real-world objects: your dog,
your desk, your television set, your bicycle etc.

 Real-world objects share two characteristics. They all have state and
behaviour.

 Object is nothing but instance (dynamic memory allocation) of a class.

 The dynamic memory allocated at run time for the members [non-static
variables] of the class is known as object.

Object: Object is an instance of class, object has state and behaviours.

An Object in java has three characteristics:


 State
 Behaviour
 Identity

State: Represents data (value) of an object.

What is state of the Object?

 The data present inside object of a class at that point of time is known as
state of the object.

Behaviour:

 Represents the behaviour (functionality) of an object such as deposit,


withdraw etc.

What is behavior of the object?

 The functionalities associated with the object => Behaviour of the


object.

 The state of the object changes from time-to-time depending up on the


functionalities that are executed on that object but whereas behaviour
of the object would not change.
Identity:

 Object identity is typically implemented via a unique ID. The value of


the ID is not visible to the external user. But it is used internally by the
PVM to identify each object uniquely.

How to Define a class?

 We can write a class to represent properties (attributes) and actions


(behaviour) of object.

 Properties can be represented by variables.


 Actions can be represented by Methods.

 We can define a class by using class keyword.

Syntax:

class className:
''' documenttation string '''
variables:instance variables,static and local variables
methods: instance methods,static methods,class methods

 Documentation string represents description of the class. Within the


class doc string is always optional. We can get doc string by using the
following 2 ways.

print(classname. __doc__)
help(classname)

Syntax to create object In Python:

referencevariable = classname()

What is a Reference variable?


 Reference variable is a variable which would be representing the address
of the object.
 Reference will act as a pointer and handler to the object.
 Since reference variable always points an object.
 In practice we call the reference variable also as an object.
 By using reference variable, we can access properties and methods of
object.

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

# instantiate the Car class


Maruti = Car("Maruti", 14)
Tata = Car("Tata", 13)

# access the class attributes


print("Maruti is a {}".format(Maruti.__class__.Type1))
print("Tata is also a {}".format(Tata.__class__.Type1))

# access the instance attributes


print("{} is {} years old".format( Maruti.name, Maruti.old))
print("{} is {} years old".format( Tata.name, Tata.old))
Output
Maruti is a Four wheeler
Tata is also a Four wheeler
Maruti is 14 years old
Tata is 13 years 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

 As noted in the corresponding docstring, the __init__() method is called the


initializer. It's equivalent to the constructor in other object-oriented languages,
and is the method that is first run when you create a new object, or new
instance of the class.

 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).

Define Method in class


class Car2:

# class attribute
Type1 = "Four wheeler"
def read(self):
self.name="Maruti"

def show(self):
print(self.name)
print(__class__.Type1)

# instantiate the Car class


obj=Car2()
obj.read()
obj.show()

 Within the Python class we can represent data by using variables.

 There are 3 types of variables are allowed.


1. Instance Variables (Object Level Variables)
2. Static Variables (Class Level Variables)
3. Local variables (Method Level Variables)

 Within the Python class, we can represent operations by using methods.


 The following are various types of allowed methods
1. Instance Methods
2. Class Methods
3. Static Methods

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

 self variable can be used to refer current class instance variable.

 By using self we can access instance variables and instance methods of


object.
In Python constructor must be contains first parameter as self.
def __init__(self):

In Python method must be contains first parameter as self.


def fun(self):

 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

Purpose Of self Variable


self . (self dot)

 which can be used to differentiate variable of class and formal parameters of


method or constructor.

"self" variable are used for two purpose, they are

 It always points to current class object.


 Whenever the formal parameter and data member of the class are similar and
PVM gets an ambiguity (no clarity between formal parameter and data
members of the class).

To differentiate between formal parameter and data member of the class, the data
members of the class must be preceded by "self".

 Syntax-:

self.data member of current class.

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.

 __new__() method in Python class is responsible for creating a new


instance object of the class. __new__() is similar to the constructor
method in other OOP (Object Oriented Programming) languages such as
C++, Java and so on.

 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.

 If we want to perform any operation at the time of object creation the


suitable place is constructor.

 In a single word constructor is a special member method which will be


called automatically whenever object is created.
 The name of the constructor should be __init__(self).

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.

 Constructor can take at least one argument (at least self)


def __init__(self):

 Per object constructor will be executed only once.

class Test:
def __init__(self):
print(" Class Test Constructor exeuction...")

# instantiate the Car class


t1=Test()
t2=Test()
t3=Test()

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")

Rules or properties of a constructor

 A constructor initializes the object immediately when it is created.


 Constructor is the first block of code that executes when an object is created.
 Constructor executes only once in the object’s life cycle.
 It can accept some arguments.

. Types of constructors in Python

 A constructor is a special kind of method which is used for initializing


the instance variables during object creation.
 We have two types of constructors in Python.
1. Default constructor
2. User defined constructor

Default constructor

class Test:
def m1(self):
print('Hello')

#create an object of class


t1=Test()

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.

Parameterized constructor example

 When we declare a constructor in such a way that it accepts the arguments


during object creation then such type of constructors is known as
Parameterized constructors.

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

More than One Python Constructor

 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

# creating object of the class


t1=Test()
t1=Test()
TypeError: __init__() missing 1 required positional argument: 'a'

class Test:
def __init__(self):
print("First constructor")
def __init__(self,a):
print("Second constructor")
self.a=a

# creating object of the class


t1=Test(10)
Output:
Second constructor

Using Default Arguments


 Even the following piece of code is simply the use of default arguments, not
constructor overloading:

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

Difference between Method and Constructor

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:

 Inside Python class 3 types of variables are allowed.


1. Instance Variables (Object Level Variables)
2. Static Variables (Class Level Variables)
3. Local variables (Method Level 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.

 For every object a separate copy of instance variables will be created.


 Instance variable is an object level variable.

Where and How we can declare Instance variables:


1. We can declare instance variable Inside Constructor by using self-variable
2. We can declare instance variable Inside Instance Method by using self-variable.
3. We can declare instance variable Outside of the class by using object reference
Variable

1. Inside Constructor by using self-variable:


 We can declare instance variables inside a constructor by using self-
keyword. Once we create object, automatically these variables will be
added to the object.

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}

2. 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.

Example:
class Demo:
def __init__(self):
self.a=10
self.b=20

def f1(self):
self.c=30

# instantiate the Demo class


d1=Demo()
print(d1.__dict__)
d1.f1()
print(d1.__dict__)
OutPut:
{'a': 10, 'b': 20}
{'a': 10, 'b': 20, 'c': 30}

3. Outside of the class by using object reference variable:


 We can also add instance variables outside of a class to a particular object.
Example:

class Demo:
def __init__(self):
self.a=10
self.b=20

def f1(self):
self.c=30

# instantiate the Demo class


d1=Demo()
print(d1.__dict__)
d1.f1()
print(d1.__dict__)
d1.d=40
print(d1.__dict__)

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)

# instantiate the Demo class


d1=Demo()
d1.info()
print("=============================")
#Outside the class instance variable, we can access by Using reference
variable
print("a= ",d1.a)
print("b= ",d1.b)
Output: -
a= 10
b= 20
=============================
a= 10
b= 20

 How We can delete Instance variables With-in Class and Outside the
class:

 We can delete instance variable by using del kwd.

 We can delete instance variable With-in class as follows


del self.variableName

 We can delete instance variable outside of class as follows


del objectreference.variableName
class Demo:
def __init__(self):
self.a=10
self.b=20
self.c=30
self.d=40
self.e=50
def removeA(self):
del self.a

# instantiate the Demo class


d1=Demo()
print(d1.__dict__)
d1.removeA()
print(d1.__dict__)

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

# instantiate the Demo class


d1=Demo()
print(d1.__dict__)
del d1.a
print(d1.__dict__)
Output:
{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}
{'b': 20, 'c': 30, 'd': 40, 'e': 50}
Note: -
 The instance variables which are deleted from one object, will not be deleted
from other objects because for each object a separate copy will be
maintained.

class Demo:
def __init__(self):
self.a=10
self.b=20
self.c=30
self.d=40
self.e=50

# instantiate the Demo class


d1=Demo()

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

# instantiate the Demo class


d1=Demo()
print("Before changing d1 => ",d1.a,d1.b)
d1.a=30
d1.b=40

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 and why we use static variable

 Suppose we want to store record of all employee of any company, in this


case employee id is unique for every employee but company name is
common for all.

 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

 This class has two instances and one static variable

 Static variables we can declare also inside constructor by using class


name
class Student:
def __init__(self,rollno,name):
Student.college_name='ITM'
self.rollno=rollno
self.name=name

 Static variables we can declare also inside instance method by using


class name
class Student:
def __init__(self,rollno,name):
self.rollno=rollno
self.name=name
def m1(self):
Student.college_name='ITM'

 Static variables we can declare also Inside classmethod by using either


class name or cls variable.

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"

How we can access static variable


 We can access static variable inside constructor by using either self or
classname
class Student:
college_Name="ITM"

def __init__(self):
#acessing static variable using self inside constructor
print(self.college_Name)

#acessing static variable using ClassName inside constructor


print(Student.college_Name)

# instantiate the Student class


s1=Student()

 We can access static variable inside instance method: by using either


self or classname

class Student:
college_Name="ITM"

def m1(self):
#acessing static variable using self inside Instance Method
print(self.college_Name)

#acessing static variable using ClassName inside Instance Method


print(Student.college_Name)

# instantiate the Student class


s1=Student()
s1.m1()

 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)

#acessing static variable using ClassName inside class Method


print(Student.college_Name)

# instantiate the Student class


s1=Student()
s1.m1()
 We can access static variable inside static method: by using classname

class Student:
college_Name="ITM"

@staticmethod
def m1():

#acessing static variable using ClassName inside static Method


print(Student.college_Name)

# instantiate the Student class


s1=Student()
s1.m1()

 We can access static variable From outside of class: by using either


object reference or classnmae
class Student:
college_Name="ITM"

# instantiate the Student class


s1=Student()

#acessing static variable using ClassName Outside the class


print(Student.college_Name)

#acessing static variable using object reference Outside the class


print(s1.college_Name)
How and Where We can modify the static variable

 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.

 We can modify static variable inside constructor using className


class Student:
college_Name="ITM"

def __init__(self):
Student.college_Name="IIT"

# instantiate the Student class


s1=Student()

#acessing static variable using ClassName Outside the class


print(Student.college_Name)#The Output:IIT

#acessing static variable using object reference Outside the class


print(s1.college_Name)#The Output:IIT

 We can modify static variable inside staticMethod using className


class Student:
college_Name="ITM"

@staticmethod
def m1():
Student.college_Name="IIT"

# instantiate the Student class


s1=Student()

#acessing static variable using ClassName Outside the class


print(Student.college_Name)#the output:ITM

#acessing static variable using object reference Outside the class


print(s1.college_Name)#the output:ITM

s1.m1()
print("After modifying static variable through static Method")

#acessing static variable using ClassName Outside the class


print(Student.college_Name)#the output:IIT

#acessing static variable using object reference Outside the class


print(s1.college_Name)#the output:IIT
 We can modify static variable inside classMethod using cls variable

class Student:
college_Name="ITM"

@classmethod
def m1(cls):
cls.college_Name="IIT"

# instantiate the Student class


s1=Student()

#acessing static variable using ClassName Outside the class


print(Student.college_Name) #the output:ITM

#acessing static variable using object reference Outside the class


print(s1.college_Name) #the output:ITM

s1.m1()
print("After modifying static variable through class Method")

#acessing static variable using ClassName Outside the class


print(Student.college_Name) #the output:IIT
#acessing static variable using object reference Outside the class
print(s1.college_Name) #the output:IIT

 We can modify static variable outside the class using className


 In this example, we have defined a static variable named college_name
we will be trying to be changed the static variable value with the help of
reference variable outside the class.
class Student:
college_Name="ITM"

# instantiate the Student class


s1=Student()

#acessing static variable using ClassName Outside the class


print(Student.college_Name)

#acessing static variable using object reference Outside the class


print(s1.college_Name)

#modifying the static variable outside class


Student.college_Name="IIT"

print("After modifying static variable outside class")

#acessing static variable using ClassName Outside the class


print(Student.college_Name)

#acessing static variable using object reference Outside the class


print(s1.college_Name)
 What happened when we are trying to modify static variable value by
using self or object reference variable.

 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"

# instantiate the Student class


s1=Student()
s1.m1()
#acessing static variable using ClassName Outside the class
print(Student.college_Name)

#acessing instance variable using object reference Outside the class


print(s1.college_Name)

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.

 If we want to access an instance variable or instance method, we must create


an object of that required class.

 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.

 An instance method is capable of creating, getting and setting new instance


attributes and calling other instance, class and static methods.

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.

 Setter and Getter Methods:


 We can set and get the values of instance variables by using getter and setter
methods.
Accessor(Getters):
 If you want to get values of the instance variables then we need to call them
getters method accessors.
syntax:
def getVariable(self):
return self.variable
Example:
def getName(self):
return self.name
def getAge(self):
return self.age
Mutator(Setters):
 If you want to modify the value of the instance variables. then we need to we
call them mutators.
syntax:
def setVariable(self,variable):
self.variable=variable
Example:
def setName(self,name):
self.name=name
Program:
class Person:
def setName(self,name):
self.name=name
def getName(self):
return self.name
def setAge(self,age):
self.age=age
def getAge(self):
return self.age

#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.

 A class method is a class-level method.

 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.

How to define a class method


 To define a class method in python, we use @classmethod decorator in
python to create a class method.
@classmethod
def method-name(cls):
method-body
Program to demonstrate the class method:
class Car:
wheels=4
@classmethod
def run(cls,name):
print('{} runs with {} wheels...'.format(name,cls.wheels))

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)

You might also like