0% found this document useful (0 votes)
5 views1 page

Oops 1 21

The document explains how to use class methods and static methods in Python. It provides examples of a class method that tracks the number of objects created and a static method for a utility function. Both types of methods can be called using the class name or an instance of the class.

Uploaded by

vishnu050621
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
0% found this document useful (0 votes)
5 views1 page

Oops 1 21

The document explains how to use class methods and static methods in Python. It provides examples of a class method that tracks the number of objects created and a static method for a utility function. Both types of methods can be called using the class name or an instance of the class.

Uploaded by

vishnu050621
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/ 1

We can call classmethod by using classname or object reference variable.

Demo Program:

1) class Animal:
2) legs=4
3) @classmethod
4) def walk(cls,name):
5) print('{} walks with {} legs...'.format(name,cls.legs))
6) Animal.walk('Dog')
7) Animal.walk('Cat')

Output
D:\python_classes>py test.py
Dog walks with 4 legs...
Cat walks with 4 legs...

Program to track the number of objects created for a class:

1) class Test:
2) count=0
3) def __init__(self):
4) Test.count =Test.count+1
5) @classmethod
6) def noOfObjects(cls):
7) print('The number of objects created for test class:',cls.count)
8)
9) t1=Test()
10) t2=Test()
11) Test.noOfObjects()
12) t3=Test()
13) t4=Test()
14) t5=Test()
15) Test.noOfObjects()

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

1) class DurgaMath:
2)
3) @staticmethod
4) def add(x,y):

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
21  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

You might also like