【问题标题】:find all members of an instance in python, excluding __init__在python中查找实例的所有成员,不包括__init__
【发布时间】:2013-06-07 06:26:00
【问题描述】:

vars 关键字给出了实例中的所有变量,例如:

In [245]: vars(a)
Out[245]: {'propa': 0, 'propb': 1}

但是,我不知道列出我的类中定义的所有可调用成员的单一解决方案(例如,请参见此处:Finding what methods an object has),我添加了这个不包括__init__ 的简单改进:

In [244]: [method for method in dir(a) if callable(getattr(a, method)) and not method.startswith('__')]
Out[244]: ['say']

比较:

In [243]: inspect.getmembers(a)
Out[243]:
[('__class__', __main__.syncher),
 ('__delattr__',
  <method-wrapper '__delattr__' of syncher object at 0xd6d9dd0>),
 ('__dict__', {'propa': 0, 'propb': 1}),
 ('__doc__', None),
 ...snipped ...
 ('__format__', <function __format__>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of syncher object at 0xd6d9dd0>),
 ('__hash__', <method-wrapper '__hash__' of syncher object at 0xd6d9dd0>),
 ('__init__', <bound method syncher.__init__ of <__main__.syncher object at 0xd6d9dd0>>),
 ('__module__', '__main__'),
 ('__setattr__',
  <method-wrapper '__setattr__' of syncher object at 0xd6d9dd0>),
 ('__weakref__', None),
 ('propa', 0),
 ('propb', 1),
 ('say', <bound method syncher.say of <__main__.syncher object at 0xd6d9dd0>>)]

或者例如:

In [248]: [method for method in dir(a) if callable(getattr(a, method)) 
                and isinstance(getattr(a, method), types.MethodType)]
Out[248]: ['__init__', 'say']

我也找到了这个方法,排除了内置例程:

In [258]: inspect.getmembers(a, predicate=inspect.ismethod)
Out[258]:
[('__init__',
  <bound method syncher.__init__ of <__main__.syncher object at 0xd6d9dd0>>),
 ('say', <bound method syncher.say of <__main__.syncher object at 0xd6d9dd0>>)]

所以,我的问题是: 你有更好的方法在 Python 2.7.X 中查找类中的所有方法(不包括__init__,以及所有内置方法)?

【问题讨论】:

  • 这个解决方案在我看来相当优雅,是不是性能不能满足您的需求?否则,我会说坚持下去。
  • @coder543,我的性能没有问题。我只是想知道我是否完成了对“Python Zen”的搜索;-)

标签: python oop python-2.7 introspection


【解决方案1】:

由于没有其他人提供更好的解决方案,我猜 Pythonic 的方式是使用 Python 的 STL:

inspect.getmembers(a, predicate=inspect.ismethod)

要排除初始化,可以使用filter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多