如何区分Python 3中的实例方法,类方法,静态方法或函数?

时间:2013-11-13 06:45:00

标签: python python-3.x introspection

我想区分Python 3中的方法和函数。此外,如果它是一个方法,我想获得相应的类。我目前的解决方案是这样的:

import types
import inspect

def function_or_method(f):
    if inspect.ismethod(f):
        if inspect.isclass(f.__self__):
            print("class method")
            klass = f.__self__
        else:
            print("instance method")
            klass = f.__self__.__class__
    elif inspect.isfunction(f): # function
        if f.__name__ != f.__qualname__: # to distiguish staticmethod and function
            print("static method")
            # HOW TO GET THE CLASS
        else:
            print("function")
    else:
        print("not function or method")

class Foo():
    def bari(self):
        pass
    @classmethod
    def barc(cls):
        pass
    @staticmethod
    def bars():
        pass

def barf():
    pass

function_or_method(Foo().bari) # instance method
function_or_method(Foo.barc) # class method
function_or_method(Foo.bars) # static method
function_or_method(barf) # function

它有效,但看起来并不优雅。而且我不确定我是否错过了什么。有谁知道更好的解决方案?

UPDATE 1 :如果是方法,我也想获得相应的类。我知道如何处理类/实例方法(参见上面的代码),但是如何获得静态方法的类呢?

2 个答案:

答案 0 :(得分:2)

您只需要获取方法的类型,但由于方法是描述符,您必须:

1 - 从实例中获取课程。 2 - 在__dict__中查找方法引用,而不是进行属性查找。

E.G:

>>> f = Foo()
>>> type(f.__class__.__dict__['bari'])
<class 'function'>
>>> type(f.__class__.__dict__['barc'])
<class 'classmethod'>
>>> type(f.__class__.__dict__['bars'])
<class 'staticmethod'>

答案 1 :(得分:0)

我认为更好的方法是使用isfunction()的{​​{1}}方法。

语法:

inspect

如果您想测试单一方法,可以通过...

进行测试
[inspect.getmembers(<module name>, inspect.isfunction)] # will give all the functions in that module

你可以使用许多谓词是函数。有关清晰的图片,请参阅{3}的Python 3文档。