0

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?

rob-gordon
  • 1,419
  • 3
  • 20
  • 38
  • Class member calls in Python are explicit with self. – cdbitesky Sep 12 '13 at 23:10
  • Eek! Semicolons! Also, getters and setters in python are almost never useful. You can just as easily use `name._bar` -- it's not private, try it out! – vroomfondel Sep 12 '13 at 23:12
  • I didn't think they were required! I just kept seeing them in tutorials! ahhh! :) – rob-gordon Sep 12 '13 at 23:15
  • Actually I end up using getters and setters because I want to do other things when I set properties. I know this is bad practice but I'm not sure what's the right alternative.. event systems?... – rob-gordon Sep 12 '13 at 23:18
  • 1
    Read the top answers to http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters. You really want to use `@property` if you want getters and setters. – D.Shawley Sep 12 '13 at 23:24

1 Answers1

1

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

interjay
  • 107,303
  • 21
  • 270
  • 254