简体   繁体   English

在Python类中使用self进行属性返回

[英]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. 我来自javascript背景,我认为这是我首先遇到这个问题的原因。

Is there any difference when using self to refer to properties of a class in method definitions. 使用self来引用方法定义中的类的属性时,有什么区别。

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. 我想我可以通过说出引用类内属性时使用self的作用来改写这个问题。 IE What if, for some strange reason, I wanted to return a global _bar variable inside of getBar() instead? IE如果由于某种奇怪的原因,我想在getBar()内返回一个全局_bar变量呢?

Your second code doesn't return the class attribute. 您的第二个代码不返回class属性。 It will return the global _bar if it exists, or raise a NameError exception otherwise. 它将返回全局_bar如果存在),否则将引发NameError异常。 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 . 您可以使用return Foo._barreturn self._bar返回一个类属性(即在所有实例之间共享的属性)。

To return an instance attribute you need to return self._bar 要返回实例属性,您需要return self._bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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