Explain the variables inside and outside of a class __init__() function in Python.

PythonServer Side ProgrammingProgramming

Class variables vs Instance Variables

All variables outside the class __init__ function in Python are class variables while those inside the same are instance variables. The difference between the class variables and instance variables is understood better by examining the code below

Example

class MyClass:
    stat_elem = 456
    def __init__(self):
        self.object_elem = 789
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.stat_elem, c1.object_elem
456 789
>>> print c2.stat_elem, c2.object_elem
456 789
# Let's try changing the static element
MyClass.static_elem = 888
>>> print c1.stat_elem, c1.object_elem
888 789
>>> print c2.stat_elem, c2.object_elem
888 789
# Now, let's try changing the object element
c1.object_elem = 777
>>> print c1.stat_elem, c1.object_elem
888 777
>>> print c2.stat_elem, c2.object_elem
888 789
raja
Published on 12-Jan-2018 13:15:44
Advertisements