2009-07-31 7 views
2

特定のインスタンスにメソッドが存在するかどうかを検出する関数を作成し、渡すことができるパラメータは何ですか?適切なパラメータでメソッドを呼び出します。私は初心者だと私はそれを行う方法を見当がつかない:(関数に関する情報を取得して呼び出す方法

+0

存在を確認するときにメソッド名を知っていますか? –

答えて

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

1

Pythonはduck typingをサポートしています - 単にインスタンス上でメソッドを呼び出す

+0

OPは、パラメータが何であるかを事前に知らないように聞こえます。実行時にその情報を照会できるようにするためです。 –

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

関連する問題