How can a function access its own attributes?

前端 未结 16 1840
再見小時候
再見小時候 2020-11-28 07:49

is it possible to access the python function object attributes from within the function scope?

e.g. let\'s have

def f():
    return          


        
16条回答
  •  情书的邮戳
    2020-11-28 07:55

    Another way to accomplish this is to define the function inside another function, and have the outer function return the inner one. Then the inner function can access itself via a closure. Here's a simple example:

    def makeFunc():
        def f():
            return f._x
        return f
    

    Then:

    >>> f = makeFunc()
    >>> f._x = "foo"
    >>> f()
    'foo'
    >>> g = f
    >>> del f
    >>> g()
    'foo'
    

提交回复
热议问题