简体   繁体   中英

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.

EG

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. IE What if, for some strange reason, I wanted to return a global _bar variable inside of getBar() instead?

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 (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM