Python Class Variables Initialization | Static | Instance

Python class variables shared by all objects, not only in python, almost every programming language. Which Variables are defined or assigned value class level is class variable in python. If a variable is assigned value or defines an Inside the class function that is called instance variables. In this tutorial, we will learn about Python class variables with simple examples.

Python Class Variables Initialization Static Instance example

Variables Scope 

  • If a Variables declared inside the class definition, but not inside a method then, function and all object access them.
  • And if Variables declared inside Python functions then it’s Instance variable, the class can’t access directly. But the object of the class can access Instance Variable, check the below example.

Python class variables Example 

Here is an example of how to define (assign value or initialization) class variables and Instance variables. Where creating an object of the class and accessing variables of the class.

class MyClass:
    cVar = 'Programming'  # Class Variable

    def __init__(self, name, roll):
        self.name = name  # Instance Variable
        self.roll = roll  # Instance Variable


# Objects of MyClass
obj1 = MyClass('EyeHunts', 1)

print(obj1.cVar)  # prints class variable

# Print Instance Variable
print(obj1.name, obj1.roll)

# Class variables can be accessed using class
print(MyClass.cVar)

Output: Programming
EyeHunts 1
Programming

QA: How to decelerated python class static variables

Variables declared inside the class definition, but not inside a function are a class or static variables, check this example.

class MyClass:
    cVar = 'Programming'  # Class Variable

print(MyClass.cVar)

Output: Programming

QA: Python class variables vs instance variables, What if class access Instance Variables?

Variables are declared in class level is class variable and variable declared Inside the class function that is called instance variables.

If class access Instance Variables, then it raises an error : AttributeError: type object 'MyClass' has no attribute 'varInst'

class MyClass:
    
    def myInstanceMethod(self):
        # Instance Variable
        varInst = 'output from an instance method'

print(MyClass.varInst)

Output:

Python class access Instance Variables output error

It can be your next interviewer question, and if you have any doubt or suggestion comment out. To know about Python class and objects must read this article –Python Classes create | Explained Objects 

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of class variables and Instance variables are in Python 3, so it may change 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.