Python Class Variables Initialization | Static | Instance

Python class variables shared by all objects, not only in python, almost every programming languages. Which Variables are defined or assigned value class level is class variable in python. If a variable is assigned value or define Inside class function that is called instance variables. 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 Variable. Where creating an object of the class and accessing variables of the class.

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.

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 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'

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 Variable 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.