Methods
Areeba Ashraf
Static Method
Class Method
Instance Method
Static Method: It is a method inside class that doesn’t use self
(which refers to object).It does some work and can be directly
using the class name . You don’t have to create object.
✓ It is utility/helper method.
Example
class Calcualtor:
@staticmethod
def add(a,b) #self is not used
return a+b
result=[Link](5,4)#object is not created
Print(“Result:”,result)
Without Static Method:
class Calculator:
def add(self,a,b):
return a+b
calc=Calculator()
Print([Link](5,3))
Use @staticmethod when your function belongs to the class
but doesn’t need to access any object or class data.
Class Method: is used when a method needs to access or
change the class itself , not a specific object of class.
• It takes cls as the first parameter instead of self.
• self refers to object.
• cls refers to the class.
Example
class Student:
school_name=‘city school’
@classmethod
def get_school(cls):
return cls.school_name
#call class method without creating object
Print(Student.get_school())
#output:City School
How to change class attributes?
Class Person:
name=‘anynomous’
@classmethod
def changename(cls,name):
[Link]=name
p1=person
P1=person()
[Link](‘Rahul Khan’)
print([Link]) #output:Rahul Khan
print([Link])
OR
class student:
name="anonymous"
def changename(self,name):
self.__class__.name="Rahul"
p1=student()
[Link](“kajol")
print([Link])
output=Rahul
•name = "anonymous" is a class variable (shared across all instances of the class).
• self.__class.__name =“Rahul” modifies the class variable not the
instance variable.
• So,even though you are passing ‘kajol”as a parameter,its not being
[Link] the value “Rahul” is hardcoded and assigned to
class variable.
Class Decorator:is a function that takes class as input,modifies and
enchances it return a new or modified class . Example @staticmethod,
@classmethod,@propertymethod.
Property Method:is a built_in feature that allows you to define a
method and access it like an attribute without using parenthesis.
class Student:
def __init__(self,phy,chem,math):
[Link]=phy
[Link]=chem
[Link]=math
@property
def percentage(self):
return str(([Link]+[Link]+[Link])/3)+"%"
s1=Student(23,45,67)
print([Link])
[Link]=86
print([Link])
print([Link])#parenthesis is not used for method it is used as attribute.
OUTPUT:45.0%
66.0%