python tutorial - Python Class | Class or Static Variables in Python - learn python - python programming




  • 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.
  • 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 - Sample - python code :

# 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('wiki', 1)
b = CSStudent('techy', 2)
 
print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.name)    # prints "wiki"
print(b.name)    # prints "techy"
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
wiki
techy
1
2
cse

Wikitechy tutorial site provides you all the learn python , free online courses python , best online python course , online learning python , python learn to code , free online course python programming , learn to program python , introduction to python course , python course , python free online course , learn python 3 online

Related Searches to Class or Static Variables in Python