Class or Static Variables in Python
Class or static variables are shared by all objects. Instance or non-static variables are different for different objects (every object has a copy of it).
For example, let a Computer Science Student be represented by class CSStudent. The class may have a static variable whose value is “cse” for all objects. And class may also have non-static members like name and roll.
In C++ and Java, we can use static keyword to make a variable as class variable. The variables which don’t have preceding static keyword are instance variables. See this for Java example and this for C++ example.
The Python approach is simple, it doesn’t require a static keyword. All variables which are assigned a value in class declaration are class variables. And variables which are assigned values inside class methods are instance variables.
# Python program to show that the variables with a value # assigned in class declaration, are class variables # Class for Computer Science Student class CSStudent: stream = 'cse' # Class Variable def __init__(self,name,roll): self.name = name # Instance Variable self.roll = roll # Instance Variable # Objects of CSStudent class a = CSStudent('Geek', 1) b = CSStudent('Nerd', 2) print(a.stream) # prints "cse" print(b.stream) # prints "cse" print(a.name) # prints "Geek" print(b.name) # prints "Nerd" print(a.roll) # prints "1" print(b.roll) # prints "2" # Class variables can be accessed using class # name also print(CSStudent.stream) # prints "cse" |
Output:
cse cse Geek Nerd 1 2 cse
This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- How to write an empty function in Python - pass statement?
- Operator Functions in Python | Set 2
- Time Functions in Python | Set-2 (Date Manipulations)
- Send mail from your Gmail account using Python
- Print Single and Multiple variable in Python
- Increment and Decrement Operators in Python
- str() vs repr() in Python
- Swap two variables in one line in C/C++, Python, PHP and Java
- Generate all permutation of a set in Python
- trunc() in Python
- Division Operators in Python
- Interesting facts about strings in Python | Set 1
- When to use yield instead of return in Python?
- How to split a string in C/C++, Python and Java?
- Interesting facts about strings in Python | Set 2 (Slicing)



