Python3 内置方法

一. 简介 

 python内置了一系列的常用函数,以便于我们使用,python英文官方文档详细说明:点击查看, 为了方便查看,将内置函数的总结记录下来。

 

二. 使用说明

   以下是Python3版本所有的内置函数:

  内置函数  
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() 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()  
delattr() hash() memoryview() set()  

1. abs()  获取绝对值

1 >>> abs(-10)
2 10
3 >>> abs(10)
4 10
5 >>> abs(0)
6 0
7 >>> a = -10
8 >>> a.__abs__()
9 10

 

2. all()  接受一个迭代器(貌似可迭代对象也可以),如果迭代器的所有元素都为真(或者为空),那么返回True,否则返回False

1 >>> tmp_1 = ['python',123]
2 >>> all(tmp_1)
3 True
4 >>> tmp_2 = []
5 >>> all(tmp_2)
6 True
7 >>> tmp_3 = [0]
8 >>> all(tmp_3)
9 False

 

3. any()  接受一个迭代器,如果迭代器里有一个元素为真,那么返回True,否则返回False

 

4. ascii()  ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。

>>> l = ["asdasddaas啊",]
>>> ascii(l)
"['asdasddaas\\u554a']"

 

5. bin(), 6. oct(),  7. hex()    三个函数功能为:将十进制数分别转换为2/8/16进制。

>>>bin(10)
'0b1010'
>>> bin(20)
'0b10100'
>>> oct(10)
'0o12'
>>> oct(20)
'0o24'
>>> oct(15)
'0o17'
>>>hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(12)
'0xc'
>>> type(hex(12))
<class 'str'>      # 字符串

 

8. bool()  用于将给定参数转换为布尔类型,如果没有参数,返回 False。bool 是 int 的子类。

>>>bool()
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(2)
True
>>> issubclass(bool, int)  # bool 是 int 子类
True

 

9. bytes()  将一个字符串转换成字节类型,语法是:class bytes([source[, encoding[, errors]]])。

从str到bytes,是编码,   比特流=str(串,encoding='utf-8')

从bytes到str,是解码,串=bytes(比特流,encoding='utf-8')

也可以使用encode()函数对字符串进行编码,转换成二进制字节数据,也可用decode()函数将字节解码成字符串。

1 >>> s = 'python'
2 >>> x = bytes(s, encoding='utf-8')
3 >>> x
4 b'python'
5 >>> a = '王'
6 >>> s = bytes(a, encoding='utf-8')
7 >>> s
8 b'\xe7\x8e\x8b'

 

10. str()  将字符类型/数值类型等转换为字符串类型

1 >>> str(b'\xe7\x8e\x8b', encoding='utf-8')  # 字节转换为字符串
2 '王'
3 >>> str(1)   # 整数转换为字符串
4 '1'

 

11. challable()  判断对象是否可以被调用,能被调用的对象就是一个callables对象,比如函数和带有__call__()的实例

1 >>> callable(max)
2 True
3 >>> callable([1, 2, 3])
4 False
5 >>> callable(None)
6 False
7 >>> callable('str')
8 False

 

12. char(i),13. ord(i)  查看十进制数对应的ASCII字符/查看某个ASCII对应的十进制数

参数i -- 可以是 10 进制也可以是 16 进制的形式的数字,数字范围为 0 到 1,114,111 (16 进制为0x10FFFF)

i是单个字符

 1 >>> chr(-1)
 2 Traceback (most recent call last):
 3   File "<pyshell#26>", line 1, in <module>
 4     chr(-1)
 5 ValueError: chr() arg not in range(0x110000)
 6 >>> chr(0)
 7 '\x00'
 8 >>> ord('\x00')
 9 0
10 >>> ord('7')
11 55

 

14. classmethod()  修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

 1 class Province:
 2     country = "中国"
 3       
 4     def __init__(self, name):
 5         self.name = name
 6       
 7     @classmethod
 8     def show(cls):  # 类方法,由类调用,最少要有一个参数cls,调用的时候这个参数不用传值,自动将类名赋值给cls
 9         print(cls)
10       
11 # 调用方法
12 Province.show()

 

15. complie()  将字符串编译成python能识别或可以执行的代码,也可以将文字读成字符串再编译

1 compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
2 将source编译为代码或者AST对象。代码对象能过通过exec语句来执行或者eval()进行求值。
3 参数source:字符串或者AST(abstract syntax trees)对象。
4 参数filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。通常设置为空。
5 参数model:指定编译代码的种类。可以指定'exec', 'eval', 'single'。
6 参数flag和dont_inherit:这两个参数为可选参数。
>>>str = "for i in range(0,10): print(i)" 
>>> c = compile(str,'','exec')   # 编译为字节代码对象 
>>> c
<code object <module> at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17

 

16. complex()

1 创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数是字符串,则不需要指定第二个参数。
2 参数real:int,long,float或字符串。
3 参数imag:int,long,float。
>>>complex(1, 2)
(1 + 2j)
 
>>> complex(1)    # 数字
(1 + 0j)
 
>>> complex("1")  # 当做字符串处理
(1 + 0j)
 
# 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex("1+2j")
(1 + 2j)

 

17. delattr()  删除对象的属性,语法:delattr(object, name)

18. getattr()   函数用于返回一个对象属性值

 getattr(object, name [, defalut])
  • object -- 对象。
  • name -- 字符串,对象属性。
  • default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')        # 获取属性 bar 值
1
>>> getattr(a, 'bar2')       # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3)    # 属性 bar2 不存在,但设置了默认值
3

19. hasattr()函数用于判断对象是否包含对应的属性

1 hasattr(object,name)
2 判断对象object是否包含名为name的特性(hasattr是通过调用getattr(object,name))是否抛出异常来实现的。
3 参数object:对象
4 参数name:特性名称
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Coordinate:
    x = 10
    y = -5
    z = 0
 
point1 = Coordinate() 
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no'))  # 没有该属性

结果
True
True
True
False

20.setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。

如果属性不存在会创建一个新的对象属性,并对属性赋值:

>>>class A():
...     name = "runoob"
... 
>>> a = A()
>>> setattr(a, "age", 28)
>>> print(a.age)
28
>>>

 

21. dict()  创建数据字典

1 >>> a = dict()  空字典
2 >>> a
3 {}
4 >>> b = dict(one = 1, two =2)
5 >>> b
6 {'one': 1, 'two': 2}
7 >>> c = dict({'one':1 ,'two':2})
8 >>> c
9 {'one': 1, 'two': 2}

 

22. dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息

1 >>> dir()
2 ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'li', 'li1', 'li2', 'li_1']
3 >>> dir(list)
4 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

23. divmod()  分别取商和余数

1 >>> divmod(20,6)
2 (3, 2)

 

24. enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

语法:enumerate(sequence, [start=0])     start是下标起始位置

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 小标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)

结果
0 one
1 two
2 three

 

25. eval()  将字符串str当成有效的表达式来求值并返回计算结果

1 >>> s = "1+2*3"
2 >>> type(s)
3 <class 'str'>
4 >>> eval(s)
5 7

 

26. exec()  执行字符串或complie方法编译过的字符串,没有返回值

exec(object[, globals[, locals]])
参数
object:必选参数,表示需要被指定的 Python 代码。它必须是字符串或 code 对象。如果 object 是一个字符串,该字符串会先被解析为一组 Python 语句,然后再执行(除非发生语法错误)。如果 object 是一个 code 对象,那么它只是被简单的执行。
globals:可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。
locals:可选参数,表示当前局部命名空间(存放局部变量),如果被提供,可以是任何映射对象。如果该参数被忽略,那么它将会取与 globals 相同的值。
>>>exec('print("Hello World")')
Hello World
# 单行语句字符串
>>> exec("print ('runoob.com')")
runoob.com
 
#  多行语句字符串
>>> exec ("""for i in range(5):
...     print ("iter time: %d" % i)
... """)
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4

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

 

27. filter()  过滤器,构造一个序列,等价于[ item for item in iterables if function(item)],

函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

>>> def x(y):
...     return y > 5
...
>>>
>>> filter(x,(1,2,3,4,5,6))
<filter object at 0x0000016D8E426F10>
>>> s = filter(x,(1,2,3,4,5,6))
>>> s
<filter object at 0x0000016D8E431130>
>>> list(s)
[6]

 

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

 1 >>> float()
 2 0.0
 3 >>> float('123')
 4 123.0
 5 >>> float(1)
 6 1.0
 7 >>> float('a')
 8 Traceback (most recent call last):
 9   File "<pyshell#45>", line 1, in <module>
10     float('a')
11 ValueError: could not convert string to float: 'a'

 

29. format()  格式化输出字符串,format(value, format_spec)实质上是调用了value的__format__(format_spec)方法

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

#也可以设置参数:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

“”“
结果为
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
”“”

#也可以向 str.format() 传入对象:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

“”“
结果为
value 为: 6
”“”
#我们可以使用大括号 {} 来转义大括号
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print ("{} 对应的位置是 {{0}}".format("runoob"))
name = input("Name:")
age = input("Age:")
print(f"{name}的年龄:{age}")
'''
这种格式化输出,推荐使用这种方式,在python3.5以上版本可以使用。



#占位符
name = 'lili'
age = 30

print('name is %s. age is %s '%(name,age))

 

30. frozenset()  创建一个不可修改的集合,返回一个冻结的集合,冻结后集合不能再添加或删除任何元素

1 frozenset([iterable])
2 set和frozenset最本质的区别是前者是可变的,后者是不可变的。当集合对象会被改变时(例如删除,添加元素),只能使用set,
3 一般来说使用fronzet的地方都可以使用set。
4 参数iterable:可迭代对象。
>>> a = frozenset([1,2,3,4,5])
>>> a
frozenset({1, 2, 3, 4, 5})
>>> a[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'frozenset' object is not subscriptable
>>> for i in a:
...     print(i)
...
1
2
3
4
5
#集合是无序的,不能通过下标来查找

 

31. globals() 函数会以字典类型返回当前位置的全部全局变量。

1 >>> a = 1
2 >>> globals()
3 {'__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'a': 1, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, '__name__': '__main__', '__package__': None, '__spec__': None}

 

32. hash() 用于获取取一个对象(字符串或者数值等)的哈希值。

python中 hash(o) 接收一个 不可变类型 的数据作为参数,提取数据的特征码
特征码是整数
相同的数据 -> 相同的结果
运行 print(hash("Traditional")) 多次,可以得到不同的结果。想要了解这个现象背后的原因,需要学习hash运算的原理。
在运行时发现了一个现象:相同字符串在同一次运行时的哈希值是相同的,但是不同次运行的哈希值不同。这是由于Python的字符串hash算法有一个启动时随机生成secret prefix/suffix的机制,
存在随机化现象:对同一个字符串输入,不同解释器进程得到的hash结果可能不同。因此当需要做可重现可跨进程保持一致性的hash,需要用到hashlib模块。[1]
>>>hash('test')            # 字符串
2314058222102390712
>>> hash(1)                 # 数字
1
>>> hash(str([1,2,3]))      # 集合
1335416675971793195
>>> hash(str(sorted({'1':1}))) # 字典
7666464346782421378
>>>
#不可变类型,str后变成字符串类型

 

33. help()  返回对象的帮助文档

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

 

34. id()  在CPython中返回对象的内存地址.返回对象的唯一标识符,标识符是一个整数

1 >>> a = 1
2 >>> id(a)
3 1588522800

 

35. input()  获取用户输入内容,返回为 string 类型

1 num = input("请输入一个数字:")
2 # 用户输入3
3 print(num)
4 # 输出结果
5 3

 

36. int(x, base=10)  将一个字符串或数值转换为一个整形

  • x -- 字符串或数字。
  • base -- 进制数,默认十进制。
1 int([x[,radix]])
2 如果参数是字符串,那么它可能包含符号和小数点。参数radix表示转换的基数(默认是10进制)。
3 它可以是[2,36]范围内的值,或者0。如果是0,系统将根据字符串内容来解析。
4 如果提供了参数radix,但参数x并不是一个字符串,将抛出TypeError异常;
5 否则,参数x必须是数值(普通整数,长整数,浮点数)。通过舍去小数点来转换浮点数。
6 如果超出了普通整数的表示范围,一个长整数被返回。
7 如果没有提供参数,函数返回0。

 

37. isinstance()  检查对象是否是类的对象,返回True或False

https://www.cnblogs.com/yunlong-study/p/13262164.html

注意鸭子类型协议,自己写的鸭子类型是false

1 isinstance(obj, cls)
2 检查obj是否是类cls的对象, 返回True 或 False
3 class Foo(object):
4     pass
5 obj = Foo()
6 isinstance(obj, Foo)

 

38. issubclass()  检查一个类是否是另一个类的子类。返回True或False

 1 issubclass(sub, super)
 2 检查sub类是否是super类的派生类(子类)。返回True 或 False
 3  
 4 class Foo(object):
 5     pass
 6    
 7 class Bar(Foo):
 8     pass
 9    
10 issubclass(Bar, Foo)  #true

 

39. iter() 关于迭代的相关疑问,可以参见博客文章

1 iter(o[, sentinel])
2 返回一个iterator对象。该函数对于第一个参数的解析依赖于第二个参数。
3 如果没有提供第二个参数,参数o必须是一个集合对象,支持遍历功能(__iter__()方法)或支持序列功能(__getitem__()方法),
4 参数为整数,从零开始。如果不支持这两种功能,将处罚TypeError异常。
5 如果提供了第二个参数,参数o必须是一个可调用对象。在这种情况下创建一个iterator对象,每次调用iterator的next()方法来无
6 参数的调用o,如果返回值等于参数sentinel,触发StopIteration异常,否则将返回该值。
#iter()的扩展用法:iter(object, sentinel)
#object:必须是一个可以callable的对象,例如方法,实现了def call(self, *args, **kwargs)方法的类
class data:
    list: list = [1, 2, 3, 4, 5, 6]
    index = 0

    def __call__(self, *args, **kwargs):
        item = self.list[self.index]
        self.index += 1
        return item

    def __iter__(self):
        self.i = iter(self.list)
        return self.i
        
        
for item in iter(data(), 3):  #每一次迭代都会调用一次__call__方法,当__call__的返回值等于3是停止迭代
    print(item)
class test: # test 类支持迭代协议,因为它定义有__iter__()函数
    def __iter__(self):
        self.result=[1,2,3]
        return iter(self.result) #返回的是可迭代对象

a = test()
print(type(a))

b = iter(a)  #b 拥有了__next__方法(next(b)),调用a的__iter__方法
print(next(b))

 

40. len()  返回对象长度,参数可以是序列类型(字符串,元组或列表)或映射类型(如字典)

 

41. list()  列表构造函数

1 list([iterable])
2 list的构造函数。参数iterable是可选的,它可以是序列,支持编译的容器对象,或iterator对象。
3 该函数创建一个元素值,顺序与参数iterable一致的列表。如果参数iterable是一个列表,将创建
4 列表的一个拷贝并返回,就像语句iterables[:]。 
#iterator对象
class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a <= 20:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration



myclass = MyNumbers()

l = list(myclass)
print(l)

 

42. locals()  打印当前可用的局部变量的字典

1 不要修改locals()返回的字典中的内容;改变可能不会影响解析器对局部变量的使用。
2 在函数体内调用locals(),返回的是自由变量。修改自由变量不会影响解析器对变量的使用。
3 不能在类区域内返回自由变量。

 

43. map()  语法:map(function, iterable, ...) 会根据提供的函数对指定序列做映射

 1 map(function, iterable,...)
 2 对于参数iterable中的每个元素都应用fuction函数,并将结果作为列表返回。
 3 如果有多个iterable参数,那么fuction函数必须接收多个参数,这些iterable中相同索引处的元素将并行的作为function函数的参数。
 4 如果一个iterable中元素的个数比其他少,那么将用None来扩展改iterable使元素个数一致。
 5 如果有多个iterable且function为None,map()将返回由元组组成的列表,每个元组包含所有iterable中对应索引处值。
 6 参数iterable必须是一个序列或任何可遍历对象,函数返回的往往是一个列表(list)。
 7  
 8 li = [1,2,3]
 9 data = map(lambda x :x*100,li)
10 print(type(data))
11 data = list(data)
12 print(data)
13  
14 运行结果:
15  
16 <class 'map'>
17 [100, 200, 300]

data = list(range(10))
print(list(map(lambda x: x * x, data)))

 

44. max()  返回给定元素里最大值

1 max(iterable [,args...][, key])
2 如果只提供iterable参数,函数返回可遍历对象(如:字符串,元组或列表)中最大的非空元素。
3 如果提供多个参数,那么返回值最大的那个参数。
4 可选参数key是单参数的排序函数。
5 如果提供key参数,必须是以命名的形式,如:max(a, b, c, key = fun)

 

45. meoryview()

函数返回给定参数的内存查看对象(memory view)。

所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问。

>>>v = memoryview('abcefg')
>>> v[1]
'b'
>>> v[-1]
'g'
>>> v[1:4]
<memory at 0x77ab28>
>>> v[1:4].tobytes()
'bce'

>>>v = memoryview(bytearray("abcefg", 'utf-8'))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b'bce'
>>>

 

46. min()  返回给定元素里最小值

1 min(iterable [,args...][, key])
2 如果只提供iterable参数,函数返回可遍历对象(如:字符串,元组或列表)中最小的非空元素。
3 如果提供多个参数,那么返回值最小的那个参数。
4 可选参数key是单参数的排序函数。
5 如果提供key参数,必须是以命名的形式,如:max(a, b, c, key = fun)

 

47. next()  返回一个可迭代数据结构(如列表)中的下一项

 

48. object()  所有新式类的父类,它的父类为空。

1 获取一个新的,无特性(geatureless)对象。Object是所有类的基类。它提供的方法将在所有的类型实例中共享。
2 该函数时2.2.版本新增,2.3版本之后,该函数不接受任何参数。

 

49. open()  打开文件

函数用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:使用 open() 函数一定要保证关闭文件对象,即调用 close() 函数。

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

语法:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明:

  • file: 必需,文件路径(相对或者绝对路径)。
  • mode: 可选,文件打开模式
  • buffering: 设置缓冲
  • encoding: 一般使用utf8
  • errors: 报错级别
  • newline: 区分换行符
  • closefd: 传入的file参数类型
  • opener:
 1 open(filename [, mode [, bufsize]])
 2 打开一个文件,返回一个file对象。 如果文件无法打开,将处罚IOError异常。
 3 应该使用open()来代替直接使用file类型的构造函数打开文件。
 4 参数filename表示将要被打开的文件的路径字符串;
 5 参数mode表示打开的模式,最常用的模式有:'r'表示读文本,'w'表示写文本文件,'a'表示在文件中追加。
 6 Mode的默认值是'r'。
 7 当操作的是二进制文件时,只要在模式值上添加'b'。这样提高了程序的可移植性。
 8 可选参数bufsize定义了文件缓冲区的大小。0表示不缓冲;1表示行缓冲;任何其他正数表示使用该大小的缓冲区;
 9 负数表示使用系统默认缓冲区大小,对于tty设备它往往是行缓冲,而对于其他文件往往完全缓冲。如果参数值被省却。
10 使用系统默认值。

 

50. pow()  幂函数

1 r = pow(2, 10)  # 2的10次方
2 print(r)
3               
4 # 输出
5 1024

 

51. print()  输出函数

1 python2中的print语句被python3中的print()函数取代。
2 如何限制print的默认换行:
3 1. python2版本下,在print输出的最后加一个逗号','
4 2. python3.4以后,print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False),将end设为空即可。
  • objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
  • sep -- 用来间隔多个对象,默认值是一个空格。
  • end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
  • file -- 要写入的文件对象。
  • flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。
import time

print("---RUNOOB EXAMPLE : Loading 效果---")

print("Loading",end = "")
for i in range(20):
    print(".",end = '',flush = True)
    time.sleep(0.5)

 

52. property()  函数的作用是在新式类中返回属性值。属性函数,调用时,就像在使用类属性。

class property([fget[, fset[, fdel[, doc]]]])
  • fget -- 获取属性值的函数
  • fset -- 设置属性值的函数
  • fdel -- 删除属性值函数
  • doc -- 属性描述信息
class People:
    def __init__(self,name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, val):
        if type(val) is not str:
            print("必须传入字符串类型")
            return
        self.__name = val

    @name.deleter
    def name(self):
        print("不让删除")
        #del self.__name
  #如果不加@,则可以这样:name = property(get_name, set_name, del_name) 括号中是函数名
obj = People("YUN") obj.name = "long" print(obj.name) del obj.name

 由于 getname() 方法中需要返回 name 属性,如果使用 self.name 的话,其本身又被调用 getname(),这将会先入无限死循环。为了避免这种情况的出现,程序中的 name 属性必须设置为私有属性,即使用 __name(前面有 2 个下划线)。

 

53. range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。

语法:range(start, stop[, step])    包前不包后

1 常用于for循环。参数必须是普通整数。
2 参数step默认值为1,参数start的默认值为0。
4 step 可以是正整数或者负整数。不可以为0,否则将处罚ValueError异常。
5 range(3)代表0,1,2.等价于range(0,3)

>>>range(5)

range(0, 5)

>>> for i in range(5):

... print(i)

... 0 1 2 3 4

>>> list(range(5))

[0, 1, 2, 3, 4]

>>> list(range(0))

[]

>>>

 

54. repr()函数将对象转化为供解释器读取的形式。返回一个对象的 string 格式。可以用eval()来执行

¥命令行下直接输出对象调用的是对象的repr方法,print输出调用的是str方法

class Spider(object):
    def __init__(self, username, password):
        self.username = username
        self.password = password


    def __repr__(self):
        return 'username: {}, password:{}'.format(self.username, self.password)



if __name__ == '__main__':
    s = Spider('12334', '2323423')
    print(repr(s))  #如果没有__str__,直接print(s),结果一样。

# 返回: username: 12334, password:2323423

 

55. reversed(seq) 反转,逆序对象,返回一个反转的迭代器。

seq -- 要转换的序列,可以是 tuple, string, list 或 range

1 reversed(seq)
2 返回一个逆序的iterator对象。参数seq必须是一个包含__reversed__()方法的对象或支持序列操作(__len__()和__getitem__())
#!/usr/bin/env python3
 
# 字符串
seqString = 'Runoob'
print(list(reversed(seqString)))
 
# 元组
seqTuple = ('R', 'u', 'n', 'o', 'o', 'b')
print(list(reversed(seqTuple)))
 
# range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
 
# 列表
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

"""
结果
['b', 'o', 'o', 'n', 'u', 'R']
['b', 'o', 'o', 'n', 'u', 'R']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]
"""

 

56. round() 返回浮点数 x 的四舍五入值,准确的说保留值将保留到离上一位更近的一端(四舍六入)。

精度要求高的,不建议使用该函数。

语法为:round( x [, n] )

  • x -- 数字表达式。
  • n -- 表示从小数点位数,其中 x 需要四舍五入,默认值为 0。
#!/usr/bin/python3

print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))

"""
结果为:
round(70.23456) :  70
round(56.659,1) :  56.7
round(80.264, 2) :  80.26
round(100.000056, 3) :  100.0
round(-100.000056, 3) :  -100.0
"""

>>> round(2.675, 2) 
2.67

 

57 set()  创建一个无序不重复元素集。https://www.cnblogs.com/yunlong-study/p/8796329.html

 

58. slice()函数实现切片对象,主要用在切片操作函数里的参数传递

语法:

class slice(stop)
class slice(start, stop[, step])

参数说明:

  • start -- 起始位置
  • stop -- 结束位置
  • step -- 间距

返回一个切片对象。

>>>myslice = slice(5)    # 设置截取5个元素的切片
>>> myslice
slice(None, 5, None)
>>> arr = range(10)
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr[myslice]         # 截取 5 个元素
[0, 1, 2, 3, 4]
>>>
 

59. sorted()函数对所有可迭代的对象进行排序操作。

sort 与 sorted 区别:

sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。

list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

sorted 语法:

sorted(iterable, key=None, reverse=False)

参数说明:

  • iterable -- 可迭代对象。
  • key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
  • reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

返回值:

返回重新排序的列表。

 1 >>> sorted([36,6,-12,9,-22])  列表排序
 2 [-22, -12, 6, 9, 36]
 3 >>> sorted([36,6,-12,9,-22],key=abs) 高阶函数,以绝对值大小排序
 4 [6, 9, -12, -22, 36]
 5 >>> sorted(['bob', 'about', 'Zoo', 'Credit'])  字符串排序,按照ASCII的大小排序
 6 ['Credit', 'Zoo', 'about', 'bob']
 7 如果需要排序的是一个元组,则需要使用参数key,也就是关键字。
 8 >>> a = [('b',2), ('a',1), ('c',0)]
 9 >>> list(sorted(a,key=lambda x:x[1]))   按照元组第二个元素排序
10 [('c', 0), ('a', 1), ('b', 2)]
11 >>> list(sorted(a,key=lambda x:x[0]))   按照元组第一个元素排序
12 [('a', 1), ('b', 2), ('c', 0)]
13 >>> sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower) 忽略大小写排序
14 ['about', 'bob', 'Credit', 'Zoo'] 
15 >>> sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower,reverse=True) 反向排序
16 ['Zoo', 'Credit', 'bob', 'about']

 

60. staticmethod() 返回函数的静态方法。该方法不强制要求传递参数。不实例化也能调用。参见:https://www.cnblogs.com/yunlong-study/p/12620916.html

 

61. str()  字符串构造函数,函数将对象转化为适于人阅读的形式。

 

62. sum()  求和

语法
以下是 sum() 方法的语法:

sum(iterable[, start])
参数
iterable -- 可迭代对象,如:列表、元组、集合。
start -- 指定相加的参数,如果没有设置这个值,默认为0。
返回值
返回计算结果。

实例
以下展示了使用 sum 函数的实例:

>>>sum([0,1,2])  
3  
>>> sum((2, 3, 4), 1)        # 元组计算总和后再加 1
10
>>> sum([0,1,2,3,4], 2)      # 列表计算总和后再加 2
12

 

63. super()  调用父类的方法

函数是用于调用父类(超类)的一个方法。

super() 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

语法

以下是 super() 方法的语法:

super(type[, object-or-type])

参数

  • type -- 类。
  • object-or-type -- 类,一般是 self

Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class FooParent(object):
    def __init__(self):
        self.parent = 'I\'m the parent.'
        print ('Parent')
    
    def bar(self,message):
        print ("%s from Parent" % message)
 
class FooChild(FooParent):
    def __init__(self):
        # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
        super(FooChild,self).__init__()    
        print ('Child')
        
    def bar(self,message):
        super(FooChild, self).bar(message)
        print ('Child bar fuction')
        print (self.parent)
 
if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar('HelloWorld')
"""
结果为:
Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.
"""

 

64. tuple()  元组构造函数,函数将可迭代系列(如列表)转换为元组。

>>>list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')

 

65. type()  显示对象所属的类型

描述
type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。

isinstance() 与 type() 区别:

type() 不会认为子类是一种父类类型,不考虑继承关系。

isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()。

语法
以下是 type() 方法的语法:

type(object)
type(name, bases, dict)  #元类
参数
name -- 类的名称。
bases -- 基类的元组。
dict -- 字典,类内定义的命名空间变量。
返回值
一个参数返回对象类型, 三个参数,返回新的类型对象。

实例
以下展示了使用 type 函数的实例:

# 一个参数实例
>>> type(1)
<type 'int'>
>>> type('runoob')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0:'zero'})
<type 'dict'>
>>> x = 1          
>>> type( x ) == int    # 判断类型是否相等
True
 
# 三个参数
>>> class X(object):
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))  # 产生一个新的类型 X
>>> X
<class '__main__.X'>
type() 与 isinstance()区别:
class A:
    pass
 
class B(A):
    pass
 
isinstance(A(), A)    # returns True
type(A()) == A        # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

 

66. vars()  

描述
vars() 函数返回对象object的属性和属性值的字典对象。

语法
vars() 函数语法:

vars([object])
参数
object -- 对象
返回值
返回对象object的属性和属性值的字典对象,如果没有参数,就打印当前调用位置的属性和属性值 类似 locals()。

实例
以下实例展示了 vars() 的使用方法:

>>>print(vars())
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> class Runoob:
...     a = 1
... 
>>> print(vars(Runoob))
{'a': 1, '__module__': '__main__', '__doc__': None}
>>> runoob = Runoob()
>>> print(vars(runoob))
{}

 

67. zip()  将对象逐一配对

描述
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

我们可以使用 list() 转换来输出列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 2.x zip() 返回的是一个列表。

如果需要了解 Pyhton2 的应用,可以参考 Python zip()。

语法
zip 语法:

zip([iterable, ...])
参数说明:

iterabl -- 一个或多个迭代器;
返回值
返回一个对象。

实例
以下实例展示了 zip 的使用方法:

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
 
>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>

 

68. __import__()

__import__() 函数用于动态加载类和函数 。

如果一个模块经常变化就可以使用 __import__() 来动态载入。
语法
__import__ 语法:
__import__(name[, globals[, locals[, fromlist[, level]]]])
参数说明:
name -- 模块名
name[必填] - 模块名称
globals - 全局变量集合,默认为None,一般不用设置。如果设置的话,常用globals()。
locals - 局部变量集合,默认为None,一般不用设置。如果设置的话,常用locals()。
fromlist - 是否导入子模块,看上去是导入模块的列表。但实际上目前它只是一个判断条件,只要设置为非空的值,且模块名称是带有子模块的,将导入子模块。例如:sys.path。当不设置时,返回sys,如果设置为非空值,则返回ntpath(path模块)。
level - 绝对或者相对导入。 英文文档:
__import__(name, globals=None, locals=None, fromlist=(), level=0) This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module(). The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement. level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details). When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. 说明:   1. 函数功能用于动态的导入模块,主要用于反射或者延迟加载模块。   2. __import__(module)相当于import module 先定义两个模块mian.py和index.py,两个文件在同一目录下: 1 2 3 4 5 6 7 8 #index.py print ('index') def sayHello(): print('hello index') def sayHelloZhCn(): print('你好 index') 1 2 3 4 5 6 7 #mian.py print ('main') index = __import__('index') dir(index) index.sayHello() index.sayHelloZhCn() 执行main.py,可以证实动态加载了index.py,__import__返回的模块也是index模块 1 2 3 4 5 C:\Users\Admin\Documents\Python3\importtest>python main.py main index hello index 你好 index 3. __import__(package.module)相当于from package import name,如果fromlist不传入值,则返回package对应的模块,如果fromlist传入值,则返回package.module对应的模块。 先定义archives包,其中包含user和role两个模块: 1 2 3 4 5 #__index__.py print ('archives.__index__') def sayHello(): print('hello archives') 1 2 3 4 5 #user.py print ('user') def sayHello(): print('hello user') 1 2 3 4 5 #role.py print ('role') def sayHello(): print('hello role') 结构如下: 修改mian.py: 1 2 3 4 5 6 #main.py print ('main') archives = __import__('archives') archives.sayHello() archives.user 执行main.py,可以证实动态加载了archives包,__import__返回的模块也是archives模块 C:\Users\Admin\Documents\Python3\importtest>python main.py main archives.__index__ hello archives Traceback (most recent call last): File "main.py", line 5, in <module> archives.user AttributeError: module 'archives' has no attribute 'user' 修改mian.py: 1 2 3 4 5 6 #main.py print ('main') archives = __import__('archives.user') archives.sayHello() print(archives.user) 执行main.py,可以证实动态加载了archives包的user模块,__import__返回的模块也是archives模块 1 2 3 4 5 6 7 C:\Users\Admin\Documents\Python3\importtest>python main.py main archives.__index__ user hello archives <module 'archives.user' from 'C:\\Users\\Admin\\Documents\\Python3\\import test\\archives\\user.py'> 修改mian.py: 1 2 3 4 5 6 #main.py print ('main') archives = __import__('archives.user',fromlist = ('user',)) archives.sayHello() print(archives) 执行main.py,可以证实动态加载了archives包的user模块,__import__返回的模块是user模块 1 2 3 4 5 6 7 C:\Users\Admin\Documents\Python3\importtest>python main.py main archives.__index__ user hello user <module 'archives.user' from 'C:\\Users\\Admin\\Documents\\Python3\\import test\\archives\\user.py'> 4. level参数,指定是使用绝对导入还是相对导入。 0(默认值)表示只执行绝对导入。

 

 

 

 

 摘自:

https://www.runoob.com/python3/python3-built-in-functions.html

https://www.cnblogs.com/xiao1/p/5856890.html

https://www.jb51.net/article/128957.htm

这篇写的不错。

https://www.zky.name/article/72.html

posted @ 2021-01-26 16:45  云long  阅读(136)  评论(0编辑  收藏  举报