遍历Python/IronPython对象方法 [英] Looping over a Python / IronPython Object Methods

查看:75
本文介绍了遍历Python/IronPython对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遍历Python对象的方法并调用它们的正确方法是什么?

What is the proper way to loop over a Python object's methods and call them?

给出对象:

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

推荐答案

您可以使用inspect模块获取类(或实例)成员:

You can use the inspect module to get class (or instance) members:

>>> 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()的第二个参数是谓词,它过滤返回列表(在这种情况下,仅返回方法对象)

getmembers() returns a list of tuples, where each tuple is (name, member). The second argument to getmembers() is the predicate, which filters the return list (in this case, returning only method objects)

这篇关于遍历Python/IronPython对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆