2008-08-29 17 views
233

Pythonオブジェクトがあれば、このオブジェクトが持つすべてのメソッドのリストを簡単に取得できますか?Pythonオブジェクトのあるメソッドの検索

あるいは、

これが不可能な場合、それは単にメソッドが呼び出されたときにエラーが発生したかどうかをチェックする以外の特定のメソッドを持っているかどうかを確認するには、少なくとも簡単な方法はありますか?

+0

関連性:https://stackoverflow.com/q/46033277/1959808 –

答えて

297

あなたが興味のあるオブジェクトに「オブジェクト」を置き換える、あなたはこのコードを使用することができます表示されます - 私はいくつかの更なる詳細を提供するべきであるうまくいけば、this siteでそれを発見し

[method_name for method_name in dir(object) 
if callable(getattr(object, method_name))] 

+0

ここで達成しようとしていることはわかりませんが、その3つの場所に「方法」があることは意味がありません。 「オブジェクト」を「あなたが興味のあるオブジェクト」に置き換えると、単一の呼び出し可能オブジェクトを持つすべての呼び出し可能オブジェクトが返されます。ポイントを理解するのを手伝ってください。 –

+0

メソッド== method_nameと呼び出し可能な(getattr(obj、method_name))] 'の場合、' [obj = {'foo': 'バー'}; method_name = '取得';メソッド== method_nameで呼び出し可能(getattr(obj、method_name));]ならば、x = [getattr(obj、method) (if(len(x)):x [0]( 'foo') '...それは本当に1行で厄介だが、コメントは改行を許さないことを知っている。 –

+0

@RichardBronosky、あなたには何の意味もありませんが、それは機能します。 – jwg

131

組み込みのdir()関数を使用して、モジュールにあるすべての属性のリストを取得できます。コマンドラインでこれを試して、その動作を確認してください。

>>> import moduleName 
>>> dir(moduleName) 

また、あなたはモジュールは、特定の属性を持っているかどうかを調べるためにhasattr(module_name, "attr_name")機能を使用することができます。

詳細については、Guide to Python introspectionを参照してください。より直接的な答えの上に

hasattr(object,"method") 
+0

'hasattr'は、Pythonオブジェクトに特定のメンバ変数またはメソッドがあるかどうかを調べるのに役立ちました。 – Akshay

23

。 'タブ'を押すと、利用可能な方法が表示され、自動補完が可能です。

そして、あなたは方法を見つけたら、試してみてください。

help(object.method) 

をpydocsを見るために、メソッドシグネチャなど

ああ... REPL

+11

OPはメソッドだけではなく属性を探しているので、さらに次のようなステップを進めたいと思います:if hasattr(obj、method)およびcallable(getattr(obj、method)): ' –

17

私はiPythonは言及しなかった場合、私は怠慢だろう:それは、特定のメソッドを持っているかどうかを確認するために

1

...それは「Easier to ask for forgiveness than permission」は確かですが方法が

呼び出されたときにエラーが発生した場合、単純にチェックする以外の特定のメソッドを持っているかどうかを確認するには、少なくとも簡単な方法がありますPythonの方法で、あなたが探しているもの:

d={'foo':'bar', 'spam':'eggs'} 
if 'get' in dir(d): 
    d.get('foo') 
# OUT: 'bar' 
33

最も単純な方法はdir(objectname)を使用することです。そのオブジェクトに利用可能なすべてのメソッドが表示されます。クールなトリック。

+0

オブジェクトの属性なので、メソッドを具体的に見つけたい場合は機能しません。 – neuronet

+0

はい。合意したしかし、私はメソッドのリストを取得するだけの他のテクニックは認識していません。たぶん最も良いアイデアは、属性とメソッドの両方のリストを取得し、を使用してそれをさらにフィルタリングすることです)。 –

+1

回答を見る – neuronet

5

ここに示したすべてのメソッドの問題は、メソッドが存在しないことを確認できないことです。

あなたが「実行時」メソッドを作成することが可能となる、

__getattr____getattribute__スルー呼び出すドットを傍受することができますPythonで

Exemple:

class MoreMethod(object): 
    def some_method(self, x): 
     return x 
    def __getattr__(self, *args): 
     return lambda x: x*2 

あなたはそれを実行する場合は、メソッドの非を呼び出すことができますオブジェクト辞書に存在する...

>>> o = MoreMethod() 
>>> o.some_method(5) 
5 
>>> dir(o) 
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method'] 
>>> o.i_dont_care_of_the_name(5) 
10 

そして、あなたはPythonでEasier to ask for forgiveness than permissionパラダイムを使用する理由、それはです。

7

特にの方法が必要な場合は、inspect.ismethodを使用してください。メソッド名の場合

:方法そのものについては

import inspect 
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))] 

import inspect 
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)] 

時々inspect.isroutine(あまりにも役立つことができ組み込み関数、Cの拡張のため、Cython "結合" コンパイラ・ディレクティブなし)。

+0

関連の答え:https://stackoverflow.com/a/1911287/1959808 –

2

一つは

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', 
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 
'__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', 
'__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 
'remove', 'reverse', 'sort'] 
2

すべてのオブジェクトのメソッドの一覧を表示する信頼できる方法はありませんを返したいオブジェクトの呼び出し可能なプロパティ名

def getAttrs(object): 
    return filter(lambda m: callable(getattr(object, m)), dir(object)) 

print getAttrs('Foo bar'.split(' ')) 

を返しますgetAttrs関数を作成することができます。 dir(object)は通常は便利ですが、場合によってはすべてのメソッドの一覧が表示されないことがあります。 dir() documentationによると "は、そのオブジェクトの有効な属性の一覧を返そうとします。

この方法の確認は既に記載されているようにcallable(getattr(object, method))で行うことができます。

15

私が何をしたいことは、このようなものであると信じています:

私の愚見で

オブジェクトから属性のリスト、組み込み関数dir()はこの仕事をすることができます君は。引数なしで呼び出された場合

DIR(...)

dir([object]) -> list of strings 

、現在のスコープ内の名前を返す:あなたのPythonシェルにhelp(dir)出力から撮影。

これ以外の場合は、指定されたオブジェクトの属性の一部とその属性から到達可能な属性のアルファベット順リストを返します。

オブジェクトが__dir__という名前のメソッドを提供する場合は、そのオブジェクトが使用されます。それ以外の場合は デフォルトのdir()ロジックが使用され、戻り値:

  • モジュールオブジェクトの場合:モジュールの属性。
  • のクラスオブジェクト:その属性、および再帰的にその基底の属性。
  • :その属性、そのクラスの属性、および は、そのクラスの基本クラスの属性を再帰的に持ちます。
  • 例えば

$ python 
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 

>>> a = "I am a string" 
>>> 
>>> type(a) 
<class 'str'> 
>>> 
>>> dir(a) 
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', 
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'_formatter_field_name_split', '_formatter_parser', 'capitalize', 
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 
'translate', 'upper', 'zfill'] 

私はあなたの問題をチェックしていたとして、私はdir()の出力の優れたフォーマットで、思考の私の列車を実証することを決めました。

dir_attributes.py(Pythonの2.7.6)

#!/usr/bin/python 
""" Demonstrates the usage of dir(), with better output. """ 

__author__ = "ivanleoncz" 

obj = "I am a string." 
count = 0 

print "\nObject Data: %s" % obj 
print "Object Type: %s\n" % type(obj) 

for method in dir(obj): 
    # the comma at the end of the print, makes it printing 
    # in the same line, 4 times (count) 
    print "| {0: <20}".format(method), 
    count += 1 
    if count == 4: 
     count = 0 
     print 

dir_attributes.py(Pythonの3.4.3)

#!/usr/bin/python3 
""" Demonstrates the usage of dir(), with better output. """ 

__author__ = "ivanleoncz" 

obj = "I am a string." 
count = 0 

print("\nObject Data: ", obj) 
print("Object Type: ", type(obj),"\n") 

for method in dir(obj): 
    # the end=" " at the end of the print statement, 
    # makes it printing in the same line, 4 times (count) 
    print("| {:20}".format(method), end=" ") 
    count += 1 
    if count == 4: 
     count = 0 
     print("") 

私は:)貢献していることを願っています。

2

オープンbashシェル(ctrl + alt + T on Ubuntu)。 Python3シェルを起動します。のメソッドを観察するオブジェクトを作成します。ちょうどそれの後にドットを2回押し、「タブ」を追加し、あなたがそのようなものが表示されます:

[email protected]:~$ python3 
Python 3.4.3 (default, Nov 17 2016, 01:08:31) 
[GCC 4.8.4] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> s = "Any object. Now it's a string" 
>>> s. # here tab should be pressed twice times 
s.__add__(   s.__rmod__(   s.istitle(
s.__class__(  s.__rmul__(   s.isupper(
s.__contains__(  s.__setattr__(  s.join(
s.__delattr__(  s.__sizeof__(  s.ljust(
s.__dir__(   s.__str__(   s.lower(
s.__doc__   s.__subclasshook__( s.lstrip(
s.__eq__(   s.capitalize(  s.maketrans(
s.__format__(  s.casefold(   s.partition(
s.__ge__(   s.center(   s.replace(
s.__getattribute__( s.count(   s.rfind(
s.__getitem__(  s.encode(   s.rindex(
s.__getnewargs__( s.endswith(   s.rjust(
s.__gt__(   s.expandtabs(  s.rpartition(
s.__hash__(   s.find(    s.rsplit(
s.__init__(   s.format(   s.rstrip(
s.__iter__(   s.format_map(  s.split(
s.__le__(   s.index(   s.splitlines(
s.__len__(   s.isalnum(   s.startswith(
s.__lt__(   s.isalpha(   s.strip(
s.__mod__(   s.isdecimal(  s.swapcase(
s.__mul__(   s.isdigit(   s.title(
s.__ne__(   s.isidentifier(  s.translate(
s.__new__(   s.islower(   s.upper(
s.__reduce__(  s.isnumeric(  s.zfill(
s.__reduce_ex__( s.isprintable(  
s.__repr__(   s.isspace(   
0

は、あなたが取得するオブジェクト

obj = [] 

list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))

としてリストを取る:

['__add__', 
'__class__', 
'__contains__', 
'__delattr__', 
'__delitem__', 
'__dir__', 
'__eq__', 
'__format__', 
'__ge__', 
'__getattribute__', 
'__getitem__', 
'__gt__', 
'__iadd__', 
'__imul__', 
'__init__', 
'__init_subclass__', 
'__iter__', 
'__le__', 
'__len__', 
'__lt__', 
'__mul__', 
'__ne__', 
'__new__', 
'__reduce__', 
'__reduce_ex__', 
'__repr__', 
'__reversed__', 
'__rmul__', 
'__setattr__', 
'__setitem__', 
'__sizeof__', 
'__str__', 
'__subclasshook__', 
'append', 
'clear', 
'copy', 
'count', 
'extend', 
'index', 
'insert', 
'pop', 
'remove', 
'reverse', 
'sort'] 
0

モジュール全体で特定のメソッドを検索するために

for method in dir(module) : 
    if "keyword_of_methode" in method : 
    print(method, end="\n") 
関連する問題