Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

class

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
like image 255
jweob Avatar asked May 09 '15 23:05

jweob


2 Answers

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.

like image 198
Peter DeGlopper Avatar answered Oct 01 '22 07:10

Peter DeGlopper


The first usage would surprise me if I were looking at your code since it would make me think the variable was being used somewhere else in the class.

Since the first is surprising and makes your intent harder to discern, I'd say the latter is more pythonic, and better in any language that works more or less the same way.

like image 29
Robert Moskal Avatar answered Oct 01 '22 08:10

Robert Moskal