循环Python / IronPython对象方法

时间:2009-05-30 04:24:47

标签: python reflection ironpython introspection python-datamodel

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

鉴于对象:

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

4 个答案:

答案 0 :(得分:9)

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

>>> 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()返回一个元组列表,其中每个元组都是(name,member)。 getmembers()的第二个参数是谓词,它过滤返回列表(在这种情况下,只返回方法对象)

答案 1 :(得分:3)

方法与功能和其他类型的可调用...

(解决Unknown帖子中评论中的问题。)

首先,应该注意的是,除了用户定义的方法之外,还有内置方法,正如http://docs.python.org/reference/datamodel.html所说的那样,内置方法“真的是一种不同的伪装内置函数“(它是C函数的包装器。)

至于用户定义的方法,正如Unknown引用的引用所说:

  

用户定义的方法对象组合   一个类,一个类实例(或None)   和任何可调用的对象(通常是一个   用户定义的函数)。

但这并不意味着“任何定义__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'>
>>> 

我不会添加更多输出,但你也可以使一个类成为另一个类或实例的属性,即使类是可调用的,你也不会得到一个方法。使用非数据描述符实现方法,因此如果您想了解有关它们如何工作的更多信息,请查找描述符。

答案 2 :(得分:0)

此代码段会调用它在obj中找到的任何内容并将结果存储在映射中,其中key是属性名称 - dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))

答案 3 :(得分:-1)

修改

丹尼尔,你错了。

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()