How can a function access its own attributes?

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

    How about using a class instead of a function and abusing the __new__ method to make the class callable as a function? Since the __new__ method gets the class name as the first parameter, it can access all the class attributes

    like in

    class f(object):
            def __new__(cls, x):
                print cls.myattribute
                return x
    

    this works as in

    f.myattribute = "foo"
    f(3)
    foo
    3
    

    then you can do

    g=f
    f=None
    g(3)
    foo
    3
    

    The issue is that even if the object behaves like a function, it is not. Hence IDEs fail to provide you with the signature.

提交回复
热议问题