weiliwei 发表于 2015-10-26 12:21:44

python decorator知识理解, 主要内容来自廖雪峰的官方网站

  本文只是我练习的记录,更详细的学习资料来源于http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000
  1. 函数也是一个对象, 对象能被赋值给变量,所以通过变量也能够调用函数
  

<pre name=&quot;code&quot; class=&quot;python&quot;>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys as yy
import re
def function_assign_to_variable():
print &quot;call function_assign_to_variable&quot;
if __name__ == &quot;__main__&quot;:
another_func = function_assign_to_variable
another_func()
print function_assign_to_variable.__name__
print function_assign_to_variable.__doc__
print yy.path
y =dir(yy)
for item in y:
print item
rr = re
print dir(rr)
  


  2. dir函数的作用
  help(dir)可以查看dir函数的帮助文档
  这部分知识来源于http://sebug.net/paper/python/ch08s06.html
  

dir()函数
  

你可以使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。

当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。

使用dir函数


例8.4 使用dir函数

$ python

>>> import sys

>>> dir(sys) # get list of attributes for sys module

['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',

'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',

'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',

'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type',

'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval',

'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding',

'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',

'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache',

'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',

'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',

'version', 'version_info', 'warnoptions']

>>> dir() # get list of attributes for current module

['__builtins__', '__doc__', '__name__', 'sys']

>>>

>>> a = 5 # create a new variable 'a'

>>> dir()

['__builtins__', '__doc__', '__name__', 'a', 'sys']

>>>

>>> del a # delete/remove a name

>>>

>>> dir()

['__builtins__', '__doc__', '__name__', 'sys']

>>>

它如何工作


首先,我们来看一下在输入的sys模块上使用dir。我们看到它包含一个庞大的属性列表。

接下来,我们不给dir函数传递参数而使用它——默认地,它返回当前模块的属性列表。注意,输入的模块同样是列表的一部分。

为了观察dir的作用,我们定义一个新的变量a并且给它赋一个值,然后检验dir,我们观察到在列表中增加了以上相同的值。我们使用del语句删除当前模块中的变量/属性,这个变化再一次反映在dir的输出中。

关于del的一点注释——这个语句在运行后被用来 删除 一个变量/名称。在这个例子中,del a,你将无法再使用变量a——它就好像从来没有存在过一样。
页: [1]
查看完整版本: python decorator知识理解, 主要内容来自廖雪峰的官方网站