2009-07-31 27 views
2

我想要創建一個函數來檢測給定實例是否存在某個方法,可以傳入哪些參數,然後使用適當的參數調用該方法。我是新手,我不知道該怎麼做:(如何獲取某個函數的信息並將其調用

+0

您是否知道檢查存在時的方法名稱? – 2009-07-31 13:50:18

回答

3

嘗試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%的機會,更好的方式中存在...

+3

+1最後一句 – Juergen 2009-07-31 13:55:07

1

Python支持duck typing - 只需調用實例上的方法

+0

聽起來OP不會提前知道參數是什麼 - 他希望能夠在運行時查詢該信息。 – 2009-07-31 13:52:16

0

您是否嘗試將參數值與具有未知簽名的函數對齊?

如何匹配參數值和參數變量?猜測?

你必須使用某種名稱匹配。

例如這樣的事情。

someObject.someMethod(thisParam=aValue, thatParam=anotherValue) 

哦。等待。這已經是Python的頭等部分了。

但是如果該方法不存在(爲了不可知的原因)。

try: 
    someObject.someMethod(thisParam=aValue, thatParam=anotherValue) 
except AttributeError: 
    method doesn't exist. 
0
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')) 

我覺得inspect模塊將是非常多的幫助你。 以上代碼使用的主要功能是dir,eval,inspect.getargspec。你可以在python文檔中獲得相關的幫助。

+0

使用getattr(obj,method_name)比使用eval要乾淨得多。 – Brian 2009-07-31 15:50:07

相關問題