【Python】Python3.7.3 - Python内置函数

文章目录

  • 系统参数
  • Python内置函数
  • abs()
  • all()
  • any()
  • ascii()
  • repr()
  • eval()
  • 空值为假,非空为真

系统参数

[tony@tony-controller bin]$ cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core)

[tony@tony-controller bin]$ uname -a
Linux tony-controller 3.10.0-957.10.1.el7.x86_64 #1 SMP Mon Mar 18 15:06:45 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

[tony@tony-controller bin]$ python3 --version
Python 3.7.3

Python内置函数

abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()

abs()

abs(x, /)
Return the absolute value of the argument.
无法取绝对值的参数会导致TypeError异常。

>>> abs(-5.58)
5.58
>>> abs(0)
0
>>> abs(1)
1
>>> abs(5+9j)
10.295630140987
>>> abs(9j)
9.0
>>> abs("abc")
Traceback (most recent call last):
  File "", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

all()

all(…)
all(iterable) -> bool
 
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.

这个函数等价于如下Python代码

def all(iterable):
    for element in iterable:
        if not element: # if bool(element) is False
            return False
    return True

空值为假,非空为真

# 空列表,返回True
>>> all([])
True

# 这不是一个空列表;这是一个列表,里面含有一个空元组。
>>> all([()])
False

# 所有的元素都不是空,所以返回True
>>> all(["Hello", 'world'])
True

# 只要有一个空元素,就返回False
>>> all(["Hello", ''])
False

any()

any(…)
any(iterable) -> bool
 
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.

这个函数等价于如下Python代码

def any(iterable):
    for element in iterable:
        if element: # if bool(element) is True
            return True
    return False

所有的空值都会被Python当做假值,其余值皆认为是真值。

# 任何一个元素为真,则返回True
>>> any(["hello", ''])
True

# 所有的元素为假,才返回False
>>> any(['',(),{}])
False

ascii()

ascii(obj, /)
Return an ASCII-only representation of an object.
 
As repr(), return a string containing a printable representation of an
object, but escape the non-ASCII characters in the string returned by
repr() using \x, \u or \U escapes. This generates a string similar
to that returned by repr() in Python 2.

给出对象的一个描述性的可打印的字符串,非ASCII字符会使用\x (十六进制),\u或者\U(Unicode码)来表示。

In [7]: print(ascii(complex(3,5)))
(3+5j)

repr()

repr(obj, /)
Return the canonical string representation of the object.
 
For many object types, including most builtins, eval(repr(obj)) == obj.

返回包含一个对象的可打印表示形式的字符串。 对于许多类型来说,该函数会尝试返回的字符串将会与该对象被传递给 eval() 时所生成的对象具有相同的值,在其他情况下表示形式会是一个括在尖括号中的字符串,其中包含对象类型的名称与通常包括对象名称和地址的附加信息。 类可以通过定义 repr() 方法来控制此函数为它的实例所返回的内容。

In [11]: print(repr(complex(3,5)))
(3+5j)

In [13]: print(repr(zip([0],[1])))
<zip object at 0x7fe2ef580c88>


In [21]: class foo:
    ...:     def __repr__(self):
    ...:         return "This is a foo object"
    ...:

In [22]: f = foo()

In [23]: print(repr(f))
This is a foo object

eval()

eval(source, globals=None, locals=None, /)
Evaluate the given source in the context oqf globals and locals.
 
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

实参是一个字符串,以及可选的 globals 和 locals。globals 实参必须是一个字典。locals 可以是任何映射对象。
 
expression 参数会作为一个 Python 表达式(从技术上说是一个条件列表)被解析并求值,使用 globals 和 locals 字典作为全局和局部命名空间。 如果 globals 字典存在且不包含以 builtins 为键的值,则会在解析 expression 之前插入以此为键的对内置模块 builtins 的字典的引用。 这意味着 expression 通常具有对标准 builtins 模块的完全访问权限且受限的环境会被传播。 如果省略 locals 字典则其默认值为 globals 字典。 如果两个字典同时省略,表达式会在 eval() 被调用的环境中执行。 返回值为表达式求值的结果。 语法错误将作为异常被报告。 例如:
 
>>> x = 1
>>> eval(‘x+1’)
2
这个函数也可以用来执行任何代码对象(如 compile() 创建的)。这种情况下,参数是代码对象,而不是字符串。如果编译该对象时的 mode 实参是 ‘exec’ 那么 eval() 返回值为 None 。
 
提示: exec() 函数支持动态执行语句。 globals() 和 locals() 函数各自返回当前的全局和本地字典,因此您可以将它们传递给 eval() 或 exec() 来使用。
 
另外可以参阅 ast.literal_eval(),该函数可以安全执行仅包含文字的表达式字符串。

空值为假,非空为真

下述“空值”会被Python当做“假值 False”,注意常量区分大小写。

  • 常量:None与False
  • 任何数值类型的0:整数0,浮点0.0,复数0j (0+0j),十进制数Decimal(0),分数Fraction(0, 1)
  • 为空的序列与集合类型:空串’’,空元组(),空列表[],空集合{},空字典{} (同空集合),空range(0)

其余值,均被认为是“真值 True”

你可能感兴趣的:(Python)