在Python方法中,使用self作为临时变量会产生什么影响? [英] Does it make a difference using self for a temporary variable in a Python method?

查看:444
本文介绍了在Python方法中,使用self作为临时变量会产生什么影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时需要在方法定义中使用临时变量,而不在方法之外使用。在下面的类定义中使用 self.MyVariable MyVariable 之间的行为是否有任何差异?



示例1: self.MyVariable



class MyClass:
def Hello(self,Name):
self.MyVariable =Hello+ Name
return self .MyVariable

示例2: MyVariable p>

  class MyClass:
def Hello(self,Name):
MyVariable =Hello+ Name
return MyVariable


解决方案

类实例,并且将在您的方法范围之外的对象上可用。后者创建一个纯粹的本地引用,它不会在方法之外使用。这更好地取决于情况,但如果它实际上只是一个临时变量使用本地(非< self )变量。



情况1:

 >> foo = MyClass()
>>>> foo.MyVariable
...
AttributeError:'MyClass'对象没有属性'MyVariable'
>>> foo.Hello('bar')
'你好吧'
>>> foo.MyVariable
'Hello bar'

案例2如上,除了 MyVariable 在调用 Hello 后仍然不是对象的属性。


I sometimes need to use temporary variables in method definitions that aren't used outside the method. Is there any difference in behaviour between using self.MyVariable and MyVariable in the class definitions below? Which is the better approach and why?

Example 1: self.MyVariable

class MyClass:
    def Hello(self, Name):
        self.MyVariable = "Hello " + Name
        return self.MyVariable

Example 2: MyVariable

class MyClass:
    def Hello(self, Name):
        MyVariable = "Hello " + Name
        return MyVariable

解决方案

The first creates a lasting reference on the class instance, and will be available on the object outside the scope of your method. The latter creates a purely local reference, which will not be available outside the method. Which is better depends on the situation, but if it's actually intended to only be a temporary variable use a local (non-self) variable.

Case 1:

>>> foo = MyClass()
>>> foo.MyVariable
...
AttributeError: 'MyClass' object has no attribute 'MyVariable'
>>> foo.Hello('bar')
'Hello bar'
>>> foo.MyVariable
'Hello bar'

Case 2 is as above, except that MyVariable is still not an attribute of the object after calling Hello.

这篇关于在Python方法中,使用self作为临时变量会产生什么影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆