What is the correct way to define class variables in Python?

PythonServer Side ProgrammingProgramming

Class variables are variables that are declared outside the__init__method. These are static elements, meaning, they belong to the class rather than to the class instances. These class variables are shared by all instances of that class. Example code for class variables 

Example

class MyClass:
  __item1 = 123
  __item2 = "abc"
  def __init__(self):
    #pass or something else

You'll understand more clearly with more code −

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 17:36:16
Advertisements