DEV Community

Cover image for   STATIC VARIABLE IN PYTHON
Priyabrat Dalbehera
Priyabrat Dalbehera

Posted on

STATIC VARIABLE IN PYTHON

                        STATIC VARIABLE
Enter fullscreen mode Exit fullscreen mode

*If the value of a variable is not varied from object to object such type of variable if is called as STATIC VARIABLE.

VARIOUS METHOD TO DECLEAR STATIC VARIABLE:

1- Within the class directly but not inside any method and constructor:

class Test:
a=1 #STATIC VARIABLE
print(Test.dict)

2-In Inside the constructor by using class Name:
class Test:
a=1
def init(self):
Test.b=2 #static variable

3-Inside instance method by using class name:

class Test:
a=1
def init(self):
Test.b=2
def f(self):
Test.c=3 #Static Variable

t=Test()
t.f()
print(Test.dict)

4-inside CLASS METHOD by using either cls or class name:

class Test:
a=1
def init(self):
Test.b=2
def f(self):
Test.c=3
@classmethod
def f1(cls):

cls.d=4 #Static Variable
Test.e=5 #Static Variable

Test.f1()
print(Test.dict)

5-Inside the STATIC METHOD by using class name:

class Test:
a=1
def init(self):
Test.b=2
def f(self):
Test.c=3
@classmethod
def f1(cls):
cls.d=4
Test.e=5
@staticmethod
def f2():
Test.f=6 #static variable

Test.f2() # In static method we call directly by class name
print(Test.dict)

6-Outside of the class by using classname:

class Test:
a=1
def init(self):
Test.b=2
def f(self):
Test.c=3
@classmethod
def f1(cls):
cls.d=4
Test.e=5
@staticmethod
def f2():
Test.f=6

Test.g=7 #Static Variable
print(Test.dict)

Top comments (0)