-1

Came across one Python Class and I am finding it hard to understand how and why its working . A simplified example of the class is :

class Test:
  def __init__(self):
    self.var = 1

  otherVar = 2

  def myPrinter(self):
    print self.__dict__  # Prints {'var': 1}
    print self.var
    print self.otherVar  # Doubt !!
    print self.__dict__  # Prints {'var': 1}

ob = Test()
ob.myPrinter()

My doubt is with the self.otherVar call not throwing an error while self.__dict__ does not show reference to otherVar

Abhimanyu singh
  • 397
  • 3
  • 9
  • 2
    It looks normal to me. Simply prints `NULL` or similar strategy. If you assign to it, then you will have it in `__dict__` output. – unalignedmemoryaccess Jul 11 '17 at 10:58
  • thanks @Adam , That sort of clears my doubts . But what I dont understand is why is the variable `otherVar` not in the scope of `myPrinter()` i.e. why cant I just do `print otherVar` inside `myPrinter()` – Abhimanyu singh Jul 11 '17 at 11:05
  • 1
    because it is a part of the class itself and must be referenced via `self.otherVar` similar to how you would call methods inside each other. – Adam Jul 11 '17 at 11:07
  • Yeah makes sense . So when will we generally use a class Variable ? I know its shared across class instances , so is that its main purpose ? – Abhimanyu singh Jul 11 '17 at 11:32

2 Answers2

1

otherVar is a class member, not instance member, that's why it doesn't show in __dict__.

It appears in self.__class__.__dict__. (this way doesn't work in Python 2.x)

By the way, otherVar member value is shared across all instances and also accessible from type object: Test.otherVar

Example here: https://trinket.io/python3/d245351e58

For a more in depth explanation check here

bakatrouble
  • 1,746
  • 13
  • 19
1

It's because otherVar is an attribute of the class, while the var you setup in the __init__ is an attribute of the instance.

The otherVar is visible to the instance, because python first tries to get the instance attribute values, if the instance doesn't have it, then it checks its class attributes. If you define a var in both with different values, things may get confusing at first.

Well, do you know that comparison that a class is like a blueprint and the instance is the object built following it, right? So, var is an extra you added while creating the instance.

If you want to see otherVar, do Test.__dict__. It won't show you var, but all the class attributes. Play a little with it and with time you are going to get used to it. Class attributes may be tricky, but extremely useful.

Jayme Tosi Neto
  • 1,189
  • 2
  • 19
  • 41