Home » Python

Are static class variables possible in Python?

Python | Are static class variables possible? Here, we are going to learn about the behavior of static class variables in Python.
Submitted by Sapna Deraje Radhakrishna, on January 19, 2020

Static variables are those whose lifetime is the entire run of the application. They exist only in single instance per class and are not initiated.

The variables declared inside the class definition and not inside a method is called a class or static variables.

Example:

class TestClass:
	static_variable = 2

The variable static_variable is accessed as follows,

    TestClass.static_variable

Output

class TestClass:
  #creates a class level variable
  static_variable = 2 

print(TestClass.static_variable)

TestClass.static_variable = 5
print(TestClass.static_variable)

But the above-created static_variable is distinct from any instance-level static_variable, so we could have the below also.

test_obj = TestClass()
test_obj.static_variable = 6

print(TestClass.static_variable, test_obj.static_variable)






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.