How can a function access its own attributes?

前端 未结 16 1799
再見小時候
再見小時候 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 08:08

    If you want it to be totally independent of the function name, you need some frame magic. For example:

    def f2():
        import inspect
        frame = inspect.currentframe()
        fname = frame.f_code.co_name
        fobj = frame.f_globals[fname]
        print fobj._x
    
    
    f2._x = 2
    f2() 
    

提交回复
热议问题