循环 Python / IronPython 对象方法

发布于 2024-07-22 06:41:38 字数 192 浏览 7 评论 0原文

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

给定对象:

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

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

Given the object:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

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

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

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

相思故 2024-07-29 06:41:38

方法与函数和其他类型的可调用对象...

(解决 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'>
>>> 

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

Methods vs. functions and other types of callables...

(To address the issue in the comments in Unknown's post.)

First, it should be noted that, in addition to user-defined methods, there are built-in methods, and a built-in method is, as the doc at http://docs.python.org/reference/datamodel.html says, "really a different disguise of a built-in function" (which is a wrapper around a C function.)

As for user-defined methods, as Unknown's cited quote says:

A user-defined method object combines
a class, a class instance (or None)
and any callable object (normally a
user-defined function).

But this does not mean that "anything that defines __call__ and is attached to an object is a method." A method is a callable, but a callable is not necessarily a method. User-defined methods are wrappers around what the quote says.

Hopefully this output (from Python 2.5.2 which I have handy) will show the distinction:

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

And - editing to add the following additional output, which is also relevant...

>>> class B(object):
    pass

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

I wont add more output, but you could also make a class an attribute of another class or instance, and, even though classes are callable, you would not get a method. Methods are implemented using non-data descriptors, so look up descriptors if you want more info on how they work.

桃扇骨 2024-07-29 06:41:38

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

This code snippet will call anything it will find in obj and store results in mapping, where key is attribute name — dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))

桃气十足 2024-07-29 06:41:38

编辑

丹尼尔,你错了。

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

Edit

Daniel, you are wrong.

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

User-defined methods

A user-defined method object combines a class, a class instance (or
None) and any callable object (normally a user-defined function).

Therefore, anything that defines __call__ and is attached to an object is a method.

Answer

The proper way to see what elements an object has is to use the dir() function.

Obviously this example only works for functions that take no arguments.

a=SomeTest()
for varname in dir(a):
    var = getattr(a, varname)
    if hasattr(var, "__call__"):
        var()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文