Python 如何获取有关函数的信息并调用它

Python 如何获取有关函数的信息并调用它,python,Python,我想创建一个函数,用于检测给定实例中是否存在方法,可以传入哪些参数,然后使用适当的参数调用该方法。我是新手,不知道如何做:(Python支持-只需在实例上调用该方法。尝试hasattr >>> help(hasattr) Help on built-in function hasattr in module __builtin__: hasattr(...) hasattr(object, name) -> bool Return whether th

我想创建一个函数,用于检测给定实例中是否存在方法,可以传入哪些参数,然后使用适当的参数调用该方法。我是新手,不知道如何做:(

Python支持-只需在实例上调用该方法。

尝试
hasattr

>>> help(hasattr)
Help on built-in function hasattr in module __builtin__:

hasattr(...)
    hasattr(object, name) -> bool

    Return whether the object has an attribute with the given name.
    (This is done by calling getattr(object, name) and catching exceptions.)
有关更高级的自省,请阅读
inspect
模块


但是首先,告诉我们为什么需要这个。有99%的可能性存在更好的方法…

您是否尝试将参数值与具有未知签名的函数对齐

如何匹配参数值和参数变量?猜猜看

你必须使用某种名称匹配

比如像这样的事情

someObject.someMethod( thisParam=aValue, thatParam=anotherValue )
等等,这已经是Python的一流部分了

但是,如果这种方法不存在(出于无法解释的原因),该怎么办

我认为
检查
模块将对您有很大帮助。

上面代码中使用的主要函数是dir、eval、inspect.getargspec
。您可以在python文档中获得相关帮助。

在检查方法是否存在时您知道方法名称吗?听起来OP好像事先不知道参数是什么-他希望能够在运行时查询该信息。使用getattr(obj,method_name)比eval干净得多。
try:
    someObject.someMethod( thisParam=aValue, thatParam=anotherValue )
except AttributeError:
    method doesn't exist.
class Test(object):
    def say_hello(name,msg = "Hello"):
        return name +' '+msg

def foo(obj,method_name):
    import inspect
    # dir gives info about attributes of an object
    if method_name in dir(obj):
        attr_info = eval('inspect.getargspec(obj.%s)'%method_name)
        # here you can implement logic to call the method
        # using attribute information
        return 'Done'
    else:
        return 'Method: %s not found for %s'%(method_name,obj.__str__)

if __name__=='__main__':    
    o1 = Test()
    print(foo(o1,'say_hello'))
    print(foo(o1,'say_bye'))