質問

与えられPythonオブジェクトなどが手軽に行うことができ一覧の取得をすべてのメソッドがこのオブジェクトですか?

または、

これが不可能な場合には、少なくとも簡単にチェックされている場合、特定の方法以外でチェックエラーが発生した場合の方法は?

役に立ちましたか?

解決

で利用することができコードを置き換え'オブジェクトのオブジェクトん:

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

ものなんだそうで このサイト.思うから。

他のヒント

利用できる内蔵 dir() 機能一覧を取得するためのすべての属性のモジュールです。そこで、コマンドラインにしていませんのでご注意ください。

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

また、利用できる hasattr(module_name, "attr_name") 機能する場合、モジュールの特定の属性。

を参照 ガイドをPython省 ます。

最も簡単な方法は使用 dir(objectname).そのまま表示すべての方法にこのオブジェクトです。涼しいですよね。

チェックされている場合、特定の方法

hasattr(object,"method")

ていると思いたいものは何かのようになります:

属性のリストからオブジェクト

私の敬意見、内蔵機能 dir() できるこのお仕事です。から help(dir) 出力ではPythonのシェル:

dir(...)

dir([object]) -> list of strings

呼び出された場合な引数、戻り、名前を現在の範囲におい

のところにそれを返しalphabetizedリストの名前を含む一部の属性の指定されたオブジェクトの属性から到達可能です。

オブジェクトが次のどれかの場合を供給という名前のメソッド __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 (Python2.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 (Python3.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("")

期待していました:).

により直接回答さんにremissばっち iPython.ヒットタブでのご利用方法は、自動補完の.

および確認する方法を試:

help(object.method) 

のpydocs方法署名等

あぁ... REPL.

場合は具体的にはたい 方法, を使用してみてください .プロジェクトを作成する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、ウェず、"結合"コンパイラの指令).

開bashシェル(ctrl+alt+T Ubuntu.開始python3シェルです。オブジェクトの作成を観察方法。だけで追加点後が終わるまで電波をやりと回"タブ"という:

 user@note:~$ 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.
 >>> import readline
 >>> readline.parse_and_bind("tab: complete")
 >>> s = "Any object. Now it's a string"
 >>> s. # here tab should be pressed twice
 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(           

問題はすべてのメソッドを示すことはできないことがありますので方法はお使いになれません。

Pythonできる遮の呼び出しス __getattr____getattribute__, で作成方法"でのランタイム"

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

その理由をご利用 りやすい免除より許可 パラダイムを。

最も簡単な方法をリストの方法のanyオブジェクトを使用 help() コマンドです。

%help(object)

でのリストを利用可能な全ての重要方法に関連したオブジェクトです。

例えば:

help(str)

作が可能で、 getAttrs 数を返しオブジェクトの呼び出し可能オブジェクトのプロパティ名

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

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

ことを思い返す

['__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']

ありませんの方法でリストのすべてのオブジェクトの方法。 dir(object) 通常、有用なものなどに利用できる可能性があるとない場合の一覧表示。による dir() 文書: "と引数 の試み へのリストを返しの有効な属性がオブジェクトです。"

チェックする方法が存在するができ callable(getattr(object, method)) 既述のようにあります。

です---が少なくとも簡単にチェックされている場合、特定の方法以外でチェックエラーが発生した場合のメソッドが呼び

ながら"りやすい免除より許可"確かにPythonic、何をお探しのもの:

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

取リストとしてオブジェクト

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']

の探索をするには、あらかじめ特定の方法で全体のモジュール

for method in dir(module) :
  if "keyword_of_methode" in method :
   print(method, end="\n")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top