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?

5
  • Class member calls in Python are explicit with self. Commented Sep 12, 2013 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! Commented Sep 12, 2013 at 23:12
  • I didn't think they were required! I just kept seeing them in tutorials! ahhh! :) Commented Sep 12, 2013 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?... Commented Sep 12, 2013 at 23:18
  • 1
    Read the top answers to stackoverflow.com/questions/6618002/…. You really want to use @property if you want getters and setters. Commented Sep 12, 2013 at 23:24

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.