Skip to content

Python class static variable | Example code

  • by

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 a 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 or suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading