Python内置函数

 

Python内置函数

我们就从比较难以理解的两个函数开始吧,先啃硬骨头T.T

1. eval(expression,globals=None,locals=None)

Python docs description:
The arguments are a string and optional globals and locals.
If provided,globals must be a dictionnary.
If provided,locals can be any mapping object.
The expression argument is parsed and evaluated as a Python expression1 using the globals and locals dictinaries as global and local namespace.
就是指定表达式所处的全局空间和局部空间,在执行语句产生的所有对象都会存到指定的空间中
If the globals dictionary is present and lacks ‘__builtins__’,the current globals are copied into globals before expression is parsed.
这句话就厉害了,因为指定了全局命名空间,所以如果代码中存在使用内置函数的语句的话,可能就找不到。python解决这个问题就是,在解析代码前,会将当前的全局复制到指定的全局空间中2 脚注中实验证明。
This means that expression normally has full access to the standard builtins 模块 and restricted environments are propagated.
If the locals dictionary is omitted it defaults to the globals dictionary.
If both dictionaries are omitted,the expression is executed in the environment where eval() is called.就是说两个空间都没指定的话,那么就使用eval()所处的环境.
The return value is the result of the evaluated expression.
eval()是动态执行表达式,如果要动态执行代码语句使用exec()。
python 提供globals()和locals()返回一个当前全局和局部的空间内容,可以指定给这两个函数作为后面的参数。

2. exec(object[,globals[,locals]])

This function supoorts dynamic execution of Python code.可以使当前代码动态的变化,动态的内容取决于参数object。object must be a string or a code object.
If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).
If it is a code object,it is simply executed.
In all cases, the code that’s executed is expected to valid as file input(see the section “file input” in the Reference Manual).
Be aware that the return and yield statements may not be used outside of functions even within the context of code passed to the exec() function.
The return value is None
In all cases,if the optional parts are omitted,the code is executed in the current scope.
If only globals is provided,it must be a dictionary,which will be used for both the global and the local variables.
If globals and locals are given,they are used for the global and local variables,respectively.
If provided,locals can be any mapping object.
Remember that at module level,globals and locals are the same dictionary.
If exec gets two separate objects as globals and locals,the code will be executed as if (好似)it were embedded(嵌套在) in a class definition.
If the globals dictionary does not contain a value for the key __builtins__ ,a reference to the dictionary of the built-in module builtins is inserted under that key.
That way you can control what builtins are available to the executed code by inserting your oun __builtins__ dictionary into globals before pasing it to exec().

牛逼的exec 和eval

3. open(…)

调用:open(file,mode=’r’,buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)

Open file and return a corresponding file object .If the file cannot be opened,an OSError is raised.
返回一个file-object对象如果file不可打开的话,抛出OSError异常
file is either a string or bytes object giving the pathname of the file to be opened or an integer file descriptor of the file to be wrapped.(If a file descriptor is given,it is closed when the returned I/O object is closed ,unless closefd is set to False)
file参数给出字节或文本对象所在文件的绝对路径或者相对路径(相对于当前工作路径)
mode is an optional string that specifies the mode in which the file is opened .It defaults to ‘r’ which means open for reading in text mode.Other common values are ‘w’ for writing (truncating the file if it already exists ) ,’x’ for exclusive(排外的) creation and ‘a’ for appending (which on some Unix systems ,means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is paltform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding .(For reading and writing raw bytes use binary mode and leave encoding unspecified )

character meaning
‘r’ open for reading(default)
‘w’ open for writing,truncating the file first
‘a’ open for writing,appending to the end of the file if it exists
‘x’ open for exclusive creation,writing,non-reading,failing if the file already exists
‘b’ binary mode
‘t’ text mode(default)
‘+’ open a disk file for updating (reading and writing)
‘U’ univeral newlines mode(deprecated弃用;不赞成)
  • 首先默认模式是’r’ 由于‘t’模式也是默认的,所以不指定’b’就使用默认的’t’,即text mode,’r’ <=> ’rt’,’w’<=>’wt’,’x’<=>’xt’,'a'<=>'at'。如果都要是字节模式,那么就把‘t’换成’b’就行了,这样open()将返回TextIOWrapper变为返回BufferedWriter。自然两种支持的其它操作就有区别了。
  • ‘x’ 模式必须是文件不存在,所以open成功最终都是写入一个空白文件中。这种模式的存在就是需求要写文件,又怕将已存在的文件如果通过’w’把文件truncate了。
  • python是要区分binary和text I/O的,文件打开是binary mode的返回一个bytes oject,是不需要decoding。而str是需要进行decoding,所以要指定text文件的编码,默认使用操作系统的编码进行解码。

buffering is an optional integer used to set the buffering policy.Pass 0 to switch buffering off(only allowed in binary mode), Pass 1 to select line buffering(only useable in text mode),and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer.When no buffering argument is given , the ddefault buffering policy works as fallows:

Binary files are buffered in fixed-size chunks;the size of the buffer is chosen using a heuristic启发式的 trying to determine the underlying devices’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE.on many system s ,the buffer will typically be 4096 or 8192 bytes long.
“Interactive”
bytes模式支持关闭buffer,文本模式支持行buffer,指定其它大于1的值,表示是指定字节块buffer大小,如果是默认的-1,二进制则根据系统的默认buffer大小,如果是文本,又分是终端式交互类型,这种是以行buffer,如果普通文本文件,就和bytes是一样的
encoding 指定decode或encode的编码。 只会存在在text mode。
errors 直接官网。简单说,和encoding参数是联动的,所以是只在text mode 的。这个参数是编码错误怎样被handled的。分级别来handle不同编码上的错误。
newline 用于text mode, 对换行符的指定,默认是使用通用的,如有特殊,可以指定。
closefd 使用False值的话,file就使用文件描述符,而不是文件名。the underlying file descriptor底层文件描述符 will be kept open when the file is closed直到文件被关闭。
opener 指定自定义的opener,打开文件的方法。

 

4. all(可迭代对象)

判断可迭代对象中,每个元素,如果有一个元素是bool(ele)->False的,all()返回False,否则返回True.可迭代对象是空返回True.

5. any(可迭代对象)

可迭代对象中,任意有一个元素是bool(ele)->True的,angy()就返回True,否则返回False。可迭代对象是空的False.

 

  1. technically speaking: a condition list—技术上讲:一个条件列表
  2. 代码>>> global_space = {“a”:1,”b”:2} >>> exec(“c = 100”,global_space) >>> print(global_space) 会打印global_space里面有了__builtins__
posted @ 2018-04-04 11:25  ZJiQi  阅读(342)  评论(1编辑  收藏  举报