Python函数是否存储为对象?

3

这段查询是与链接相关的,以进一步了解以下内容:

在函数的情况下,您有一个对象,该对象具有某些字段, 其中包含字节码代码、它具有的参数数量等。

我的问题:

1)我如何将一个函数表示为对象?(NPE在此回答了这个问题)

2)我如何将高阶函数表示为对象?

3)我如何将模块表示为对象?例如'import operator'

4)像'+' '>' '!=' '==' '='这样的操作符也映射到某些对象方法吗?例如对于表达式“check = 2 < 3”,是否在内部调用类型(2)或类型(3)的某个方法来评估'<'运算符?


glglgl -- 按照要求提出了单独的查询 - overexchange
3
我假设你是在继续之前的某个问题。Stack Overflow上的每个问题应该是自包含的。你应该让这个问题易于阅读和理解,而不需要访问任何链接。就目前情况而言,很难确定你实际的问题是什么。 - Asad Saeeduddin
在Python中,我们处理的所有内容都是“对象”。 - Nishant Nawarkhede
@Sham,你没有解释清楚那个问题到底不清楚在哪里。我也认为你所问的完全是另外一件事情... - glglgl
@g.d.d.c 我已经修改了查询语句,你能否重新打开这个问题? - overexchange
1个回答

6

这段话的意思是,在Python中,函数和其他对象一样。

例如:

In [5]: def f(): pass

现在,f 是一个类型为 function 的对象:
In [6]: type(f)
Out[6]: function

如果你仔细地查看它,它包括很多字段:
In [7]: dir(f)
Out[7]: 
['__call__',
 ...
 'func_closure',
 'func_code',
 'func_defaults',
 'func_dict',
 'func_doc',
 'func_globals',
 'func_name']

拿一个例子来说,f.func_name是函数的名称:

In [8]: f.func_name
Out[8]: 'f'

f.func_code 包含了代码:

In [9]: f.func_code
Out[9]: <code object f at 0x11b5ad0, file "<ipython-input-5-87d1450e1c01>", line 1>

如果你真的很好奇,你可以进一步深入了解:
In [10]: dir(f.func_code)
Out[10]: 
['__class__',
 ...
 'co_argcount',
 'co_cellvars',
 'co_code',
 'co_consts',
 'co_filename',
 'co_firstlineno',
 'co_flags',
 'co_freevars',
 'co_lnotab',
 'co_name',
 'co_names',
 'co_nlocals',
 'co_stacksize',
 'co_varnames']

等等。

(上面的输出是使用Python 2.7.3生成的。)


import sys print(sys.version) 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)] def doNothing():pass
doNothing.func_name Traceback (most recent call last): File "<pyshell#33>", line 1, in <module> doNothing.func_name AttributeError: 'function' object has no attribute 'func_name' doNothing.func_code Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> doNothing.func_code AttributeError: 'function' object has no attribute 'func_code'
- overexchange
7
在Python 3中,您应该使用__name____code__代替func_namefunc_code - user2357112
@Sham,你已经看到dir(doNothing)会显示你拥有的属性。那些看起来像这样的属性可能是你真正想要找的。例如,如果你在2.x中寻找func_code,你在3.x中看到了一个__code__-->你找到了你要找的东西。 - glglgl
如果它是高阶函数,我需要查看哪些属性才能知道传递进来的函数? - overexchange

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接