Python内置函数(3)

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

内置函数(原文)
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() 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()
Python内置函数.png

21、exec()

a)描述

原文:
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements 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.
中文:
在全局变量和局部变量上下文中执行给定的源。
源可以是表示一个或多个Python语句的字符串,也可以是compile()返回的代码对象。
全局变量必须是字典,局部变量可以是任何映射,默认为当前全局变量和局部变量。
如果只提供全局变量,则局部变量默认为全局变量。
诠释:
exec 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。

b)语法

exec 的语法:exec(object[, globals[, locals]])

c)参数

object:必选参数,表示需要被指定的Python代码。它必须是字符串或code对象。如果object是一个字符串,该字符串会先被解析为一组Python语句,然后在执行(除非发生语法错误)。如果object是一个code对象,那么它只是被简单的执行。
globals:可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。
locals:可选参数,表示当前局部命名空间(存放局部变量),如果被提供,可以是任何映射对象。如果该参数被忽略,那么它将会取与globals相同的值。

d)返回值

exec 返回值永远为 None。

e)实例

实例1:

exec('print("Hello World!")')
# 单行语句字符串
exec("print ('kevin.com')")
#  多行语句字符串
exec("""for i in range(5):
    print ("iter time: %d" % i)
    """)

运行结果:

Hello World!
kevin.com
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4

实例2:

x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
    y = 20
    exec(expr)
    exec(expr, {'x': 1, 'y': 2})
    exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
func()

运行结果:

60
33
34

22、filter()

a)描述

原文:
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.
中文:
filter(function or None, iterable)——> filter object
返回一个迭代器,该迭代器产生的iterable项对应的函数(项)为真。如果function为None,则返回为True的项。
诠释:
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

b)语法

filter() 方法的语法:filter(function, iterable)

c)参数

function:判断函数。
iterable:可迭代对象。

d)返回值

返回一个迭代器对象。

e)实例

实例1(过滤出列表中的所有奇数):

def is_odd(n):
    return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)

运行结果:

[1, 3, 5, 7, 9]

实例2(过滤出1~100中平方根是整数的数):

import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)

运行结果:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

23、float()

a)描述

float() 函数用于将整数和字符串转换成浮点数。

b)语法

float()方法的语法:class float([x])

c)参数

x:整数或字符串。

d)返回值

返回浮点数。

e)实例
print("float(1):",float(1))
print("float(112):",float(112))
print("float(-123.6):",float(-123.6))
print("float('123'):",float('123'))     # 字符串

运行结果:

float(1): 1.0
float(112): 112.0
float(-123.6): -123.6
float('123'): 123.0

24、format()

a)描述

原文:
Return value.__format__(format_spec)
format_spec defaults to the empty string.
See the Format Specification Mini-Language section of help('FORMATTING') for details.
中文:
返回value.__format__(format_spec)
format_spec默认为空字符串。
有关详细信息,请参阅帮助(“FORMATTING”)的格式规范Mini-Language部分。
诠释:
format()增强了字符串格式化的功能,基本语法是通过 {} 和 : 来代替以前的 %,format 函数可以接受不限个参数,位置可以不按顺序。

实例(str.format() 格式化数字):

print("{:.2f}".format(3.1415926))

运行结果:

3.14
数字 格式 输出 描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:>10d} 13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d} 13 中间对齐 (宽度为10)
11 '{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
进制

^, <, > 分别是居中、左对齐、右对齐,后面带宽度,: 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -(空格)表示在正数前加空格。
bdox 分别是二进制、十进制、八进制、十六进制。
说明:我们可以使用大括号 {} 来转义大括号。

b)实例

实例1(可以接受不限个参数,位置可以不按顺序。):

print('"{} {}".format("hello", "world"):',"{} {}".format("hello", "world"))  # 不设置指定位置,按默认顺序
print('"{0} {1}".format("hello", "world"):',"{0} {1}".format("hello", "world"))  # 设置指定位置
print('"{1} {0} {1}".format("hello", "world"):',"{1} {0} {1}".format("hello", "world"))  # 设置指定位置

运行结果:

"{} {}".format("hello", "world"): hello world
"{0} {1}".format("hello", "world"): hello world
"{1} {0} {1}".format("hello", "world"): world hello world

实例2(设置参数):

print("网站名:{name}, 地址: {url}".format(name="凯文超市", url="www.kevin.com"))
# 通过字典设置参数
site = {"name": "凯文超市", "url": "www.kevin.com"}
print("网站名:{name}, 地址: {url}".format(**site))
# 通过列表索引设置参数
my_list = ['凯文超市', 'www.kevin.com']
print("网站名:{0[0]}, 地址: {0[1]}".format(my_list))  # "0" 是必须的

运行结果:

网站名:凯文超市, 地址: www.kevin.com
网站名:凯文超市, 地址: www.kevin.com
网站名:凯文超市, 地址: www.kevin.com

实例3(向 str.format() 传入对象):

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value为:{0.value}'.format(my_value))  # "0" 是可选的

运行结果:

value为:6

实例4(使用大括号 {} 来转义大括号):

print ("{} 对应的位置是 {{0}}".format("kevin"))

运行结果:

kevin 对应的位置是 {0}

实例5(如果参数format_spec未提供,则和调用str(value)效果相同,转换成字符串格式化):

>>> format(3.1415936)
'3.1415936'
>>> str(3.1415926)
'3.1415926'

实例6(对于不同的类型,参数format_spec可提供的值都不一样):

#字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))

#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3,'b') #转换成二进制
'11'
>>> format(97,'c') #转换unicode成字符
'a'
>>> format(11,'d') #转换成10进制
'11'
>>> format(11,'o') #转换成8进制
'13'
>>> format(11,'x') #转换成16进制 小写字母表示
'b'
>>> format(11,'X') #转换成16进制 大写字母表示
'B'
>>> format(11,'n') #和d一样
'11'
>>> format(11) #默认和d一样
'11'

#浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267,'e') #科学计数法,默认保留6位小数
'3.141593e+08'
>>> format(314159267,'0.2e') #科学计数法,指定保留2位小数
'3.14e+08'
>>> format(314159267,'0.2E') #科学计数法,指定保留2位小数,采用大写E表示
'3.14E+08'
>>> format(314159267,'f') #小数点计数法,默认保留6位小数
'314159267.000000'
>>> format(3.14159267000,'f') #小数点计数法,默认保留6位小数
'3.141593'
>>> format(3.14159267000,'0.8f') #小数点计数法,指定保留8位小数
'3.14159267'
>>> format(3.14159267000,'0.10f') #小数点计数法,指定保留10位小数
'3.1415926700'
>>> format(3.14e+1000000,'F')  #小数点计数法,无穷大转换成大小字母
'INF'

#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'

25、frozenset()

a)描述

frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

b)语法

frozenset() 函数语法:class frozenset([iterable])

c)参数

iterable:可迭代的对象,比如列表、字典、元组等等。

d)返回值

返回新的 frozenset 对象,如果不提供任何参数,默认会生成空集合。

e)实例
a = frozenset(range(10))     # 生成一个新的不可变集合
print("a:",a)
b = frozenset('kevin')    # 创建不可变集合
print("b:",b)

运行结果:

a: frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
b: frozenset({'e', 'k', 'n', 'v', 'i'})

26、getattr()

a)描述

原文:
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.
中文:
getattr(object, name[, default])—>value
从对象中获取命名属性;getattr(x, 'y')等于x.y。
当给定默认参数时,当属性不存在时返回;否则,在这种情况下会引发异常。
诠释:
getattr() 函数用于返回一个对象属性值。

b)语法

getattr 语法:getattr(object, name[, default])

c)参数

object:对象。
name:字符串,对象属性。
default:默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

d)返回值

返回对象属性值。

e)实例

实例1:

class A(object):
     bar = 1
a = A()
print("getattr(a, 'bar'):",getattr(a, 'bar'))        # 获取属性 bar 值
print("getattr(a, 'bar2', 3):",getattr(a, 'bar2', 3))    # 属性 bar2 不存在,但设置了默认值
# print("getattr(a, 'bar2'):",getattr(a, 'bar2'))       # 属性 bar2 不存在,触发异常

运行结果:

getattr(a, 'bar'): 1
getattr(a, 'bar2', 3): 3
Traceback (most recent call last):
  File "D:/Python_Project/Temp.py", line 1166, in 
    print("getattr(a, 'bar2'):",getattr(a, 'bar2'))       # 属性 bar2 不存在,触发异常
AttributeError: 'A' object has no attribute 'bar2'

实例2:

class A(object):
     def set(self, a, b):
         x = a
         a = b
         b = x
         print("a = {}, b = {}".format(a, b))
a = A()
c = getattr(a, 'set')
c(a='1', b='2')

运行结果:

a = 2, b = 1

27、globals()

a)描述

原文:
Return the dictionary containing the current scope's global variables.
NOTE: Updates to this dictionary will affect name lookups in the current global scope and vice-versa.
中文:
返回包含当前作用域的全局变量的字典。
注意:这个字典的更新将影响当前全局范围内的名称查找,反之亦然。

b)语法

globals() 函数语法:globals()

c)参数

d)返回值

返回全局变量的字典。

e)实例
a = 'kevin'
print(globals())    # globals 函数返回一个全局变量的字典,包括所有导入的变量。

运行结果:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000212788A0970>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': 'D:/Python_Project/Temp.py', '__cached__': None, 'a': 'kevin'}

28、hasattr()

a)描述

原文:
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
中文:
返回对象是否具有给定名称的属性。
这是通过调用getattr(obj, name)捕获AttributeError。

b)语法

hasattr 语法:hasattr(object, name)

c)参数

object:对象。
name:字符串,属性名。

d)返回值

如果对象有该属性返回 True,否则返回 False。

e)实例
class Coordinate:
    x = 10
    y = -5
    z = 0
point1 = Coordinate()
print("hasattr(point1, 'x'):",hasattr(point1, 'x'))
print("hasattr(point1, 'y'):",hasattr(point1, 'y'))
print("hasattr(point1, 'z'):",hasattr(point1, 'z'))
print("hasattr(point1, 'no'):",hasattr(point1, 'no'))  # 没有该属性

运行结果:

hasattr(point1, 'x'): True
hasattr(point1, 'y'): True
hasattr(point1, 'z'): True
hasattr(point1, 'no'): False

29、hash()

a)描述

原文:
Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true.
中文:
返回给定对象的哈希值。
两个比较相等的对象也必须具有相同的哈希值,但反过来不一定正确。
诠释:
hash() 函数可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary。
在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。
hash() 函数的对象字符不管有多长,返回的 hash 值都是固定长度的,也用于校验程序在传输过程中是否被第三方(木马)修改,如果程序(字符)在传输过程中被修改hash值即发生变化,如果没有被修改,则 hash 值和原始的 hash 值吻合,只要验证 hash 值是否匹配即可验证程序是否带木马(病毒)。

b)语法

hash 语法:hash(object)

c)参数

object -- 对象。

d)返回值

返回对象的哈希值。

e)实例

实例1:

print("hash('test'):",hash('test'))            # 字符串
print("hash(1):",hash(1))                 # 数字
print("hash(str([1,2,3])):",hash(str([1,2,3])))      # 集合
print("hash(str(sorted({'1':1}))):",hash(str(sorted({'1':1})))) # 字典

运行结果:

hash('test'): 85748363395829820
hash(1): 1
hash(str([1,2,3])): -1739346109313768372
hash(str(sorted({'1':1}))): 4803048949047724432

实例2:

class Test:
    def __init__(self, i):
        self.i = i
for i in range(10):
    t = Test(1)
    print(hash(t), id(t))

运行结果:

162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632
162349547608 2597592761728
162349529977 2597592479632

实例3:

name1='正常程序代码'
name2='正常程序代码带病毒'
print("hash(name1):",hash(name1))
print("hash(name2):",hash(name2))

运行结果:

hash(name1): -6174195686864483401
hash(name2): 8746497541882159753

30、help()

a)描述

原文:
Define the builtin 'help'.
This is a wrapper around pydoc.help that provides a helpful message when 'help' is typed at the Python interactive prompt.
Calling help() at the Python prompt starts an interactive help session.
Calling help(thing) prints help for the python object 'thing'.
中文:
定义构建“帮助”。
这是pydoc的包装。在Python交互式提示符中键入“help”时提供有用信息的帮助。
在Python提示符下调用help()启动交互式帮助会话。
调用help(thing)打印python对象“thing”的帮助。

b)语法

help 语法:help([object])

c)参数

object:对象。

d)返回值

返回对象帮助信息。

e)实例
help('sys')  # 查看 sys 模块的帮助
help('str')  # 查看 str 数据类型的帮助
a = [1, 2, 3]
help(a)  # 查看列表 list 帮助信息
help(a.append)  # 显示list的append方法的帮助

运行结果:

……显示帮助信息……(此处省略)

你可能感兴趣的:(Python内置函数(3))