2014-03-28 38 views
3

该查询与link延续,进一步了解了这一点:Python函数是否存储为对象?

In the case of functions, you have an object which has certain fields, which contain e. g. the code in terms of bytecode, the number of parameters it has, etc.

我的问题:

1)如何我想象被表示为一个对象(NPE在这里回答了这个问题的功能? )

2)怎样被可视化表示为对象的高阶函数?

3)如何我预想模块被表示为对象?说“进口经营者在”

4)是否像“+”“>”“!=”“==”“=”也被映射到某一对象的方法运营商?说expr的“检查= 2 < 3”,这是否内部调用类型(2)或式(3)来评价“<”运算符的一些方法?

+0

glglgl - 按要求 – overexchange

+3

我假设你想从其他一些问题继续单独查询升高。堆栈溢出的每个问题应该是自包含的。您无需访问任何链接即可使这个问题清晰易懂。按照现状,很难说出你的实际问题是什么。 –

+0

我们在python中处理的所有东西都是'object'。 – fledgling

回答

6

所有这一切,说的是,在Python,功能就像任何其他对象。

例如:

In [5]: def f(): pass 

现在ffunction类型的对象:

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生产。)

+0

>>> import sys >>> print(sys.version) 3.2.3(默认,2012年4月11日,07:12:16)[MSC v.1500 64 bit(AMD64)] >>> def doNothing ():pass >>> doNothing。FUNC_NAME 回溯(最近通话最后一个): 文件 “”,1号线,在 doNothing.func_name AttributeError的: '功能' 对象有没有属性 'FUNC_NAME' >>> doNothing.func_code 回溯(最近最后调用): 文件 “”,1号线,在 doNothing.func_code AttributeError的: '功能' 对象有没有属性 'func_code' – overexchange

+6

@Sham:在Python 3中,你要使用'__name__'和'__code__'而不是'func_name'和'func_code'。 – user2357112

+0

@Sham你已经看到'dir(doNothing)'显示你有什么属性。看起来像这些你正在寻找的那些可能是你真正想要的。例如,当你在2.x上找到'func_code'时,你会在3.x上看到一个'__code__' - 你找到了你想要的东西。 – glglgl

相关问题