rob-gordon
rob-gordon

Reputation: 1488

Using self for property return in python class

I come from a javascript background which I think is the reason I have this question in the first place.

Is there any difference when using self to refer to properties of a class in method definitions.

E.G.

class Foo:
  _bar = 15;

  def getBar(self):
    return self._bar;

vs.

class Foo:
  _bar = 15;

  def getBar(self):
    return _bar;

I guess I could rephrase the question by saying what are the effects of using self when referring to properties inside the class. I.E. What if, for some strange reason, I wanted to return a global _bar variable inside of getBar() instead?

Upvotes: 0

Views: 82

Answers (1)

interjay
interjay

Reputation: 110203

Your second code doesn't return the class attribute. It will return the global _bar if it exists, or raise a NameError exception otherwise. This is because the class scope is not automatically looked up from methods - only function scope and global scope is looked up when looking up variables.

You can return a class attribute (i.e. one which is shared between all instances) with either return Foo._bar or return self._bar.

To return an instance attribute you need to return self._bar

Upvotes: 1

Related Questions