Python class static variable | Example code

Which variables declared inside the class definition, but not inside a method are class or static variables in Python.

This is different from C++ and Java, but not so different from C#, where a static member can’t be accessed using a reference to an instance.

When defining some member variable outside any member method, the variable can be either static or non-static depending on how the variable is expressed.

  • CLASSNAME.var is static variable
  • INSTANCENAME.var is not static variable.
  • self.var inside class is not static variable.
  • var inside the class member function is not defined.

Python class static variable example

Simple example code.

class MyClass:
    i = "Static Variable"


print(MyClass.i)

Output:

Python class static variable

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.