dtc
dtc

Reputation: 1849

Python self: Do I have to pass self into a function to refer to self?

Question is confusing. Here's an example.

class some_class():
  some_var = 5
  def some_fun(self):
     def another_fun():
         return self.some_var

This is okay right? I don't have to have: another_fun(self) to call self? I actually tested it and it works. I just wanted some clarification because it makes me a bit unsure.

Upvotes: 0

Views: 174

Answers (2)

rodrigo
rodrigo

Reputation: 98398

In your case it is not needed because another_fun is nested into the other functions, so it captures the local names from that function, and that includes self. Actually, any name accessible from some_fun will also be accessible from another_fun.

This is what some call a closure, and it's great to write functions that create functions. The classical example is:

def MultiplyBy(x):
    def M(y):
        return x * y
    return M

Double = MultiplyBy(2)
Triple = MultiplyBy(3)

print Double(10), Triple(10)

That will print 20 30.

Upvotes: 5

BrenBarn
BrenBarn

Reputation: 251408

Yes, when you define one function inside another, the inner function can read variables from the outer one. This is nothing specific to self. It works for all variables in all functions:

>>> def outer():
...     a = 2
...     def inner():
...         print a
...     inner()
>>> outer()
2

In Python 2, you cannot rebind the outer variable in the inner function (i.e., you cannot do a = 3 inside inner above). In Python 3 you can do this with the nonlocal statement.

However, why are you doing this? In the first place, your code above doesn't even call another_fun, so what it does is immaterial. In general defining functions inside other functions is a bit of a strange thing. There are certainly legitimate cases for doing it (e.g., decorators), but in many cases it's likely to cause confusion.

Upvotes: 2

Related Questions