Search code examples
pythonperformanceclassmethodsclass-method

Class method: Where is the difference between function(self) and function?


I am a bit confused.

The following two python code snippets both return the same values:

First:

class Test():

    def __init__(self):
        None


    def outer_function(self):
        self.i = "This is the outer function" 

        def inner_function():
            y = "This is the inner function"

            return print(y)

        
        value_from_inner_function = inner_function()
        return print(self.i)

testClass = Test()
testClass.test_function()

Second:

class Test():

    def __init__(self):
        None


    def outer_function(self):
        self.i = "This is the outer function" 

        def inner_function(self):
            self.y = "This is the inner function"

            return print(self.y)

        
        value_from_inner_function = inner_function(self)
        return print(self.i)

testClass = Test()
testClass.test_function()

Both snippets return.

This is the inner function
This is the outer function

I am wondering, which of both cases should one use? My assumption is, that the inner function is only installed to be used by the outer class method (in this example the outer_function).

So there is no need to instantiation, as the outer class method can access it.

Hence, I guess that the first snippet is the one which is "more" correct. Is that so?

And if that is true, are there any noteworthy "performance" differences between snippet 1 and 2?


Solution

  • In the first version, y is a local variable of inner_function(). It goes away when the function returns.

    In the second version. self.y is an attribute of the object. Assigning it makes a permanent change to the object, so you could reference it after the inner function returns. E.g.

    class Test():
    
        def __init__(self):
            None
    
    
        def outer_function(self):
            self.i = "This is the outer function" 
    
            def inner_function(self):
                self.y = "This is the inner function"
    
                return print(self.y)
            
            value_from_inner_function = inner_function(self)
            return print(self.i)
    
    testClass = Test()
    testClass.test_function()
    print(testClass.y)