Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
What is Class or Static Variables in Python ?
All objects share class or static variables. An instance or non-static variables are different for different objects .
in python, it doesn’t require a static keyword
All variables which are assigned a value in the class declaration are class variables. And variables that are assigned values inside methods are instance variables.
File name : index.py
File name : index.py
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"
# Now if we change the stream for just a it won't be changed for b
a.stream = 'ece'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'cse'
# To change the stream for all instances of the class we can change it
# directly from the class
CSStudent.stream = 'mech'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'mech'
Output:
cse
cse
Geek
Nerd
1
2
cse
ece
cse
ece
mech
File name : index.py
File name : index.py
File name : index.py
File name : index.py
File name : index.py