
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Class or Static Variables in Python?
When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.
Class or static variable are quite distinct from and does not conflict with any other member variable with the same name. Below is a program to demonstrate the use of class or static variable −
Example
class Fruits(object): count = 0 def __init__(self, name, count): self.name = name self.count = count Fruits.count = Fruits.count + count def main(): apples = Fruits("apples", 3); pears = Fruits("pears", 4); print (apples.count) print (pears.count) print (Fruits.count) print (apples.__class__.count) # This is Fruit.count print (type(pears).count) # So is this if __name__ == '__main__': main()
Result
3 4 7 7 7
Another example to demonstrate the use of variable defined on the class level −
Example
class example: staticVariable = 9 # Access through class print (example.staticVariable) # Gives 9 #Access through an instance instance = example() print(instance.staticVariable) #Again gives 9 #Change within an instance instance.staticVariable = 12 print(instance.staticVariable) # Gives 12 print(example.staticVariable) #Gives 9
output
9 9 12 9
- Related Articles
- Class and Static Variables in C#
- Class and Static Variables in Java
- Declare static variables and methods in an abstract class in Java
- How do I create static class data and static class methods in Python?
- Static variables in Java
- Static Variables in C
- Class method vs static method in Python
- What are static methods in a Python class?
- Final static variables in Java
- Static and non static blank final variables in Java
- Initialization of static variables in C
- Templates and Static variables in C++
- Static class in Java
- Static class in C#
- Kotlin static methods and variables

Advertisements