Does it make a difference using self for a temporary variable in a Python method?

前端 未结 4 576
独厮守ぢ
独厮守ぢ 2021-01-06 02:27

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.MyVaria

4条回答
  •  独厮守ぢ
    2021-01-06 02:52

    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.

提交回复
热议问题