Site icon DataFlair

Python Static Variables and Methods

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

 
#Program for static variables,method and class method
# class Test:
#     def __init__(self):
#         self.n=10
#     def increment(self):
#         self.n=self.n+1

# #calling
# T1=Test()
# T2=Test()
# T1.increment()
# T1.increment()
# T1.increment()

# print("T1=",T1.n)
# print("T2=",T2.n)

# Static variable
# class Test:
#     n=10  # static variable
    
#     def increment(self):
#         Test.n=Test.n+1

# #calling
# T1=Test()
# T2=Test()
# T1.increment()
# T1.increment()
# T1.increment()
# T2.increment()
# T2.increment()
# T2.increment()
# Test.n=Test.n+1
# print("T1=",T1.n)
# print("T2=",T2.n)
# print("Test.n=",Test.n)

# class Test:
#     n=10  # static variable  # class variable
    
#     @staticmethod
#     def increment():
#         Test.n=Test.n+1

#     def increment1(self):
#        # self.n=self.n+1 # local variable
#         Test.n=Test.n+1

#     @classmethod
#     def increment2(cls):
#         cls.n=cls.n+1


# #calling
# T1=Test()
# T1.increment()
# T1.increment1()
# T1.increment2()
# print(Test.n)

#calling
# T1=Test()
# T2=Test()
# T1.increment()
# T1.increment()
# T1.increment()
# T2.increment()
# T2.increment()
# T2.increment()
# Test.increment()
# Test.increment()
# Test.increment()
# Test.n=Test.n+1
# print("T1=",T1.n)
# print("T2=",T2.n)
# print("Test.n=",Test.n)

Program 2

class Student:
        clgname="TechVidvan"  #static variable
        def __init__(self,rno,name):
            self.rno=rno
            self.name=name
      
        def display(self):
            print(self.rno)        
            print(self.name)        
            print(Student.clgname)        

#calling

S1=Student(101,"Vikas")
S2=Student(102,"Ramesh")
S3=Student(103,"Aakash")
S4=Student(104,"Ravi")
S1.display()
S2.display()
S3.display()
S4.display()

 

Exit mobile version