1

I can do this:

def f(n):
    f.data = 3.14
    return n ** 2
f(10), f.data

Out[8]:

(100, 3.14)

My understanding is that in f.data, the name f binds to the function object in the outer scope. It looks a bit awkward, but self doesn't work:

def f(n):
    self.data = 3.14
    return n ** 2
f(10), f.data
---------------------------------------------------------------------------

NameError: global name 'self' is not defined

Is there an equivalent of self for referencing function attributes from the inside?

usual me
  • 8,338
  • 10
  • 52
  • 95
  • 2
    Don't do this. If you need to store state across function invocations, use a class. – Marcin Sep 11 '14 at 14:49
  • No. Besides, the whole thing looks like globals in disguise: why not just return an extra value? – bereal Sep 11 '14 at 14:49
  • 2
    `self` is just the conventional name for the first argument to an instance method, not a magic value the refers to its containing function. Your code is fragile, as your function could be bound to a name other than `f`, and `f` could change, leaving your function referring to something other than itself with the global name `f`. – chepner Sep 11 '14 at 15:13
  • 1
    Maybe this link helps you http://stackoverflow.com/questions/3109289/how-can-python-function-access-its-own-attributes – fenix688 Sep 11 '14 at 15:21

0 Answers0