您的位置:首页 > 编程语言 > Python开发

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

2014-08-02 14:49 393 查看
本文只是我练习的记录,更详细的学习资料来源于http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000

1. 函数也是一个对象, 对象能被赋值给变量,所以通过变量也能够调用函数

<pre name="code" class="python">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys as yy
import re

def function_assign_to_variable():
print "call function_assign_to_variable"

if __name__ == "__main__":
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
——它就好像从来没有存在过一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: