Python中的函数对象? [英] Are functions objects in Python?

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

问题描述

我总是在Python中听到这个声明(例如,当你传递函数等装饰器等话题时),但从来没有真正看到过这个陈述。例如,可以创建一个只有一个抽象方法的类 c ,该方法被一个集合调用

 即类c:
@abstractmethod
def method_to_be_called_by():
...

让您可以拥有

  c(无论需要什么参数)

I在这里我的理解可能会有些失望,我只是好奇这是什么人的意思。

你正在寻找对于 __调用__ 方法。函数对象有这样的方法:

 >>> def foo():pass 
...
>>> foo .__ call__
<方法包装器'__call__'在0x106aafd70处的函数对象>

不是Python解释器循环实际上在遇到Python函数对象时使用该方法;在大多数情况下,实现中的优化直接跳转到包含的字节码。



但是你可以在你自己的自定义类中使用它:

  class Callable(object):
def __init __(self,name):
self.name = name

def __call __(self,greeting):
return'{},{}!'。格式(greeting,self.name)
 >>> p $ p> 

class Callable(object):
... def __init __(self,name):
... self.name = name
... def __call __(self,greeting):
... return'{},{}!'。format(greeting,self.name)
...
>>> Callable('World')('Hello')
'Hello,World!'

当您使用 Python创建函数对象 def 语句您使用

    >>> def foo():pass 
...
>>> foo
<函数foo在0x106aafd70>
>>> lambda:None
< function< lambda>在0x106d90668>

您可以将其与使用字面语法创建字符串或整数或列表进行比较:

  listobject = [1,'two'] 

上面创建了3个对象而没有调用类型,Python根据所使用的语法为您完成了这一切。这同样适用于函数。

自己创建一个可能会更复杂一点;您至少需要一个代码对象并引用全局名称空间:

 >>> function_type = type(lambda:None)
>>> function_type
< type'function'>
>>> function_type(foo .__ code__,globals(),'bar')
< 0x106d906e0处的函数栏>

这里我通过重用函数来创建一个函数对象类型,从 foo 函数获取代码对象;函数类型不是内置名称,但类型确实存在,可通过在现有函数实例上调用 type()来获得。



我也传入了我的解释器的全局命名空间和名称;后者是一个可选的论点;该名称是从代码对象中取得的。


I always hear this statement in Python (for topics such as decorators, etc. when you are passing functions, etc.) but have never really seen an elaboration on this.

For example is it possible to create a class c that has only one abstract method that is called with a set of opened and closed brackets.

i.e class c:
       @abstractmethod
       def method_to_be_called_by():
        ... 

so you can have

c(whatever parameters are required)

I could be way off the mark with my understanding here, I was just curious about what people meant by this.

解决方案

You are looking for the __call__ method. Function objects have that method:

>>> def foo(): pass
... 
>>> foo.__call__
<method-wrapper '__call__' of function object at 0x106aafd70>

Not that the Python interpreter loop actually makes use of that method when encountering a Python function object; optimisations in the implementation jump straight to the contained bytecode in most cases.

But you can use that on your own custom class:

class Callable(object):
    def __init__(self, name):
        self.name = name

    def __call__(self, greeting):
        return '{}, {}!'.format(greeting, self.name)

Demo:

>>> class Callable(object):
...     def __init__(self, name):
...         self.name = name
...     def __call__(self, greeting):
...         return '{}, {}!'.format(greeting, self.name)
... 
>>> Callable('World')('Hello')
'Hello, World!'

Python creates function objects for you when you use a def statement, or you use a lambda expression:

>>> def foo(): pass
... 
>>> foo
<function foo at 0x106aafd70>
>>> lambda: None
<function <lambda> at 0x106d90668>

You can compare this to creating a string or an integer or a list using literal syntax:

listobject = [1, 'two']

The above creates 3 objects without ever calling a type, Python did that all for you based on the syntax used. The same applies to functions.

Creating one yourself can be a little more complex; you need to have a code object and reference to a global namespace, at the very least:

>>> function_type = type(lambda: None)
>>> function_type
<type 'function'>
>>> function_type(foo.__code__, globals(), 'bar')
<function bar at 0x106d906e0>

Here I created a function object by reusing the function type, taking the code object from the foo function; the function type is not a built-in name but the type really does exist and can be obtained by calling type() on an existing function instance.

I also passed in the global namespace of my interpreter, and a name; the latter is an optional argument; the name is otherwise taken from the code object.

这篇关于Python中的函数对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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