How to distinguish an instance method, a class method, a static method or a function in Python 3?

后端 未结 2 1158
不知归路
不知归路 2021-01-06 16:48

I want to distinguish between methods and functions in Python 3. Furthermore, I want to get the corresponding class if it is a method. My current solution is like this:

2条回答
  •  無奈伤痛
    2021-01-06 17:07

    You just need to get the type of the method, but since methods are descriptors, you have to :

    1 - Get the class out of the instance. 2 - Look up the method reference in __dict__ instead of making an attribute lookup.

    E.G :

    >>> f = Foo()
    >>> type(f.__class__.__dict__['bari'])
    
    >>> type(f.__class__.__dict__['barc'])
    
    >>> type(f.__class__.__dict__['bars'])
    
    

提交回复
热议问题