質問

Python オブジェクトのメソッドをループして呼び出す適切な方法は何ですか?

オブジェクトを考えると:

class SomeTest():
  def something1(self):
    print "something 1"
  def something2(self):
    print "something 2"

正しい解決策はありません

他のヒント

あなたは、クラス(またはインスタンス)のメンバーを取得するためのモジュールを調べる使用することができます:

>>> class C(object):
...     a = 'blah'
...     def b(self):
...             pass
... 
...
>>> c = C()
>>> inspect.getmembers(c, inspect.ismethod)
[('b', <bound method C.b of <__main__.C object at 0x100498250>>)]

getmembers()タプルのリスト、各タプルは(名前、メンバー)を返します。 getmembers第2引数は()戻り値のリストをフィルタリング述語

(この場合、唯一の方法オブジェクトを返す)であります

メソッド vs.関数やその他の種類の呼び出し可能オブジェクト...

(Unknown の投稿のコメントで問題に対処するため。)

まず、ユーザー定義メソッドに加えて組み込みメソッドがあることに注意してください。組み込みメソッドは次のとおりです。 http://docs.python.org/reference/datamodel.html 「実際には、組み込み関数の別の偽装」 (C 関数のラッパーです) と言っています。

ユーザー定義メソッドについては、Unknown の引用文に次のように書かれています。

ユーザー定義のメソッドオブジェクトは、クラス、クラスインスタンス(またはなし)、および呼び出し可能なオブジェクト(通常はユーザー定義の関数)を組み合わせます。

しかし、これは「何かを定義するもの」という意味ではありません。 __call__ メソッドは呼び出し可能ですが、呼び出し可能は必ずしもメソッドであるとは限りません。ユーザー定義メソッドは、引用文の内容を包むラッパーです。

この出力 (私が手元にある Python 2.5.2 からのもの) で違いがわかるといいのですが:

IDLE 1.2.2      
>>> class A(object):
    x = 7


>>> A  # show the class object
<class '__main__.A'>
>>> a = A()
>>> a  # show the instance
<__main__.A object at 0x021AFBF0>
>>> def test_func(self):
    print self.x


>>> type(test_func)  # what type is it?
<type 'function'>
>>> dir(test_func)  # what does it have?
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__',
 '__getattribute__', '__hash__', '__init__', '__module__', '__name__',
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
 'func_doc', 'func_globals', 'func_name']
>>> # But now let's put test_func on the class...
>>> A.test = test_func
>>> type(A.test)  # What type does this show?
<type 'instancemethod'>
>>> dir(A.test)  # And what does it have?
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__',
 '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class',
 'im_func', 'im_self']
>>> # See, we just got a wrapper, and the function is in 'im_func'...
>>> getattr(A.test, 'im_func')
<function test_func at 0x0219F4B0>
>>> # Now to show bound vs. unbound methods...
>>> getattr(a.test, 'im_self') # Accessing it via the instance
<__main__.A object at 0x021AFBF0>
>>> # The instance is itself 'im_self'
>>> a.test()
7
>>> getattr(A.test, 'im_self') # Accessing it via the class returns None...
>>> print getattr(A.test, 'im_self')
None
>>> # It's unbound when accessed that way, so there's no instance in there
>>> # Which is why the following fails...
>>> A.test()

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    A.test()
TypeError: unbound method test_func() must be called with A instance as
first argument (got nothing instead)
>>>

そして - 次の追加出力を追加する編集。これも関連します...

>>> class B(object):
    pass

>>> b = B()
>>> b.test = test_func  # Putting the function on the instance, not class
>>> type(b.test)
<type 'function'>
>>> 

これ以上の出力は追加しませんが、クラスを別のクラスまたはインスタンスの属性にすることもできます。その場合、クラスは呼び出し可能であっても、メソッドは取得されません。メソッドは非データ記述子を使用して実装されるため、メソッドがどのように機能するかについて詳しく知りたい場合は、記述子を調べてください。

このコードスニペットは、キーは属性名であり、それはマッピングでobjや店舗の結果で見つける何かを呼び出します - dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))

編集

ダニエル、あなたは間違っている。

http://docs.python.org/reference/datamodel.htmlする

  

ユーザー定義方法

     

は、ユーザー定義の方法の目的は、のクラス、クラスのインスタンスを結合する(又は   なし)との任意の呼び出し可能オブジェクトの(通常はユーザ定義関数)。

したがって、__call__を定義し、オブジェクトに取り付けられているものは方法である。

回答

オブジェクトが持っているものの要素を参照するための適切な方法は、DIR()関数を使用することである。

もちろんこの例では唯一の引数を取りません機能のために働くます。

a=SomeTest()
for varname in dir(a):
    var = getattr(a, varname)
    if hasattr(var, "__call__"):
        var()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top