Python进阶篇03-内置函数
内置函数
abs()
返回数字的绝对值
语法:abs(x)
,x为数值表达式:整数、浮点数、复数
返回值:返回x的绝对值,若x为复数,则返回复数的大小
>>> abs(-5)
5
>>> abs(-12.27)
12.27
>>> abs(12+0.2j)
12.001666550941998
all()
判断可迭代参数中所有元素是否都为True(元素除了 0、空、None、False外都是True)
语法:all(iterable)
,接收一个可迭代参数
返回值:若可迭代参数中所有元素都为True,则返回True,否则返回False
>>> all('hello')
True
>>> all([1, 2, 'a'])
True
>>> all([0, 1, 2, 'a'])
False
>>> all([1, 2, 'a', ''])
False
>>> all((1, 2, 3, []))
False
>>> all([]) #
True
注意
函数all()
等价于
def all(iterable):
for element in iterable:
if not element:
return False
return True
- 当可迭代参数中有空列表、空元组等空序列元素时,因为这些空序列的布尔值都为False,所以此时的
all(iterable)
返回值为False(因为可迭代序列中有空序列元素时,遍历此序列时,遇到空元素会返回False) - 当参数为空列表、空元组、空字符串等空序列时,
all()
返回True(这是因为,当参数为空序列时,不会进入for循环,会直接return True)
all()
判断可迭代参数中是否有一个元素为True(元素除了 0、空、None、False外都是True)
语法:all(iterable)
,接收一个可迭代参数
返回值:可迭代参数中只要有一个元素为True,则返回True,否则返回False
>>> any('world')
True
>>> any([1, 2, 3, ''])
True
>>> any(['', 0])
False
>>> any([])
False
ascii()
返回一个表示对象的字符串
语法:ascii(object)
,参数为一个对象
返回值:返回一个表示参数对象的字符串,对于ascii编码的字符原样输出,对于传入对象的非ascii编码字符以转义字符的形式输出
>>> ascii('waaa')
"'waaa'"
>>> ascii([1, 2, 3])
'[1, 2, 3]'
>>> ascii(abs)
'<built-in function abs>'
>>> ascii('中国')
"'\\u4e2d\\u56fd'"
bin()
返回一个整型或长整型数值的二进制表示
语法:bin(x)
,x为一个int类型或者long int的数值,不能为浮点数、复数
返回值:返回参数的二进制表示,返回值中的'0b'表示数据是二进制类型
>>> bin(8)
'0b1000'
>>> bin(32769)
'0b1000000000000001'
bool()
返回给定参数的布尔值
语法:bool(x)
,参数非必选
返回值:参数的布尔值,True或者False,无参数则为False
>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool()
False
bytearray()
返回一个新字节数组
语法:bytearray([source[, encoding[, errors]]])
,可不传参数,这个字节数组中的元素是可变的,并且每个元素都在 0 <= x < 256范围内
返回值:字节数组
- 如果source为整数,则返回一个source长度的初始化字节数组;
- 如果source为字符串,则encoding参数必传,按照encoding将字符串转换为字节序列;
- 如果source为可迭代类型,则其中的每个元素都必须在 0 <= x < 256范围内;
- 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray;
- 不传参数时,返回一个初始化为0个元素的字节数组;
>>> bytearray(6)
bytearray(b'\x00\x00\x00\x00\x00\x00')
>>> bytearray('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
>>> bytearray('hello', 'utf-8')
bytearray(b'hello')
>>> bytearray([1, 3, 5])
bytearray(b'\x01\x03\x05')
>>> bytearray([1, 3, 5, 256])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: byte must be in range(0, 256)
>>> bytearray()
bytearray(b'')
bytes()
返回一个新的bytes(字节串)对象
字节串是Python3中新增的概念,它不是一个基础类型,可以将字节串与字符串作对比,这样就很好理解,字节串的最小单位是字节、字符串的最小单位是字符,字节串和字符串都是不可变序列。
bytes()
的基础语法与bytearray()
相同,前者是后者的不可变版本,即bytearray()
返回的字节数组中的元素是可变的,可以通过索引去修改元素的值,而bytes()
返回的字节串对象是不可变的,无法修改其元素的值。
>>> x = bytearray([1, 2, 3])
>>> x[1] = 8
>>> x
bytearray(b'\x01\x08\x03')
callable()
用于检查对象是否可调用
语法:callable(object)
,传入一个对象
返回值:若传入的对象可调用,返回True,不可调用则返回False
- 函数、方法、匿名函数、类都为可调用,都返回True;
- 对于类的实例,实现了
__call__
方法的类实例为可调用的,返回True,未实现的则返回False
>>> callable('hello')
False
>>> callable(sorted)
True
>>> callable(bool)
True
class A:
def test(self):
print('test')
class B:
def __call__(self, *args, **kwargs):
pass
def test(self):
print('1')
a = A()
b = B()
print(callable(A)) # True
print(callable(B)) # True
print(callable(a)) # False
print(callable(b)) # True
chr()
返回整数对应的ASCII字符
语法:chr(x)
,x为10进制或者16进制的整数
返回值:数值对应的ASCII字符
>>> chr(90)
'Z'
>>> chr(0x30)
'0'
>>> chr(48)
'0'
classmethod
修饰符,修饰的函数不需要实例化即可被类本身调用
语法:@classmethod
,写在类中需要修饰的函数上一行,被修饰的函数第一个参数需要是表示自身类的cls
class A:
def __init__(self):
self.name = 'mike'
self.age = 18
def test(self):
print(self.name)
@classmethod
def test2(cls):
print('不需要实例化即可调用')
# A.test() 直接调用test,会报错,因为需要实例化后,通过实例化的类进行调用
A.test2() # test2不用实例化即可调用
a = A()
a.test()
compile()
将字符串编译为字节代码
语法:compile(source, filename, mode[, flags[, dont_inherit]])
- source,必需,要编译的资源,可以为字符串或者AST(抽象语法树)对象
- filename,必需,源所来自的文件的名称,如果源不是来自文件,可以编写任何内容
- mode,必需,指定编译代码的种类,可为:exec(源为语句块时)、eval(源为单个表达式)、single(源为单个交互式语句)
- flags,可选。如何对源进行编译。默认为 0。
- dont_inherit,可选。如何对源进行编译。默认为 False。
返回值:返回可执行的代码对象
>>> x = compile('3+2', '', 'eval')
>>> x
<code object <module> at 0x7fed2949ab30, file "", line 1>
>>> eval(x)
>>> s = """
... a = 2
... b = 3
... print(a+b)
... """
>>> y = compile(s, '', 'exec')
>>> exec(y)
5
complex()
将参数转换为复数
语法:complex([real[, imag]])
,real可以为:int、long、float、字符串,imag可以为:int、long、float,当第一个参数为字符串时,不需要填写第二个参数;当字符串中为复数时,+旁不可以有空格
返回值:返回复数
>>> complex(8)
(8+0j)
>>> complex(3, 7)
(3+7j)
>>> complex(12.36)
(12.36+0j)
>>> complex('5.1')
(5.1+0j)
>>> complex('3+2j') # +旁不可以有空格
(3+2j)
delattr()
删除对象的属性
语法:delattr(object, name)
,object-对象,name-属性名,需要为字符串
返回值:无
class A:
def __init__(self):
self.name = 'mike'
self.age = 18
def test(self):
print(self.name)
@classmethod
def test2(cls):
print('不需要实例化即可调用')
delattr(A, 'x')
a = A()
print(a.x)
----------
AttributeError: 'A' object has no attribute 'x'
dict()
创建字典
语法:
dict(**kwargs)
,参数传递关键字参数,如dict(x=1, y=2, z=3)
dict(mapping[, **kwargs])
,参数为:映射类型+关键字参数,关键字参数为可选,字典为Python中唯一的映射类型,如dict({'x':1, 'y': 2, 'z': 3}, a=4, b=5, c=6)
dict(iterable[, **kwargs])
,参数为:可迭代对象+关键字参数,关键字参数为可选,可迭代对象必须可构造成键值对,如dict([('x', 1), ('y',2), ('z', 3)])
返回值:构造好的字典
divmod()
返回一个包含商和余数的元组
语法:divmod(a, b)
,a和b都为非复数的数字
返回值:
- 如果a和b都为整数,返回的值为 (a//b, a%b),即商为向下取整除,返回的两个值都为整数
- 如果a或者b为浮点数时,返回的值为 (math.floor(a/b), a%b),即商为对 a/b 的浮点数向下取整(下即取小值(注意复数)),返回的两个值都是浮点数
- 如果a%b的结果非0,则它的正负号和b相同
>>> divmod(9, 2)
(4, 1)
>>> divmod(9, 2.1)
(4.0, 0.5999999999999996)
>>> divmod(9, -2.1)
(-5.0, -1.5000000000000004)
>>> 9/-2.1 # 向下取整为-5
-4.285714285714286
enumerate()
将可迭代的对象组合成一个索引序列
语法:enumerate(sequence[, start=0])
,sequence-可迭代对象,start-下标起始位置,默认为0
返回值:返回enumerate枚举对象
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> enumerate(seasons) # 返回的enumerate对象,可直接进行遍历、可使用list()转换后打印
<enumerate object at 0x7fd4e94818c0>
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=2)) # 下标从2开始
[(2, 'Spring'), (3, 'Summer'), (4, 'Fall'), (5, 'Winter')]
>>> for i, d in enumerate(seasons):
... print(i, d)
...
0 Spring
1 Summer
2 Fall
3 Winter
eval()
执行一个字符串表达式,并返回表达式的值
语法:eval(expression)
,接收一个字符串表达式
返回值:返回该表达式的值
>>> eval('3+5')
8
>>> eval("'this is a test'")
'this is a test'
>>> eval("['a', 'b', 'c']")
['a', 'b', 'c']
exec()
执行存储在字符串或者文件中的Python语句
语法:exec(object)
,object为字符串或者code对象。exec()
能执行比eval()
更复杂的ython语句
返回值:None,当执行的Python语句有输出时会输出,但其本身返回值是None
>>> exec('print(3+5))
8
>>> res = exec('print(3+5)')
8
>>> print(res)
None
>>> exec("""
... for i in range(3):
... print(i)
... """)
0
1
2
filter()
过滤序列
语法:filter(function, iterable)
,function-函数,用来过滤序列的条件,iterable-需要过滤的序列。将序列中每个参数传递给函数进行判断,返回True或False,将结果为True的元素放到新的列表中。
返回值:迭代器对象
>>> list(filter(bool, [0, 1, True, '', 2, None]))
[1, True, 2]
getattr()
返回对象的属性值
语法:getattr(object, name[, default])
,object-对象,name-该属性的名称,default-默认返回值,若该对象没有对应属性时,若不提供此参数,则会触发AttributeError
返回值:该属性的值
>>> class People:
... sex = [0, 1]
...
>>> getattr(People, 'sex')
[0, 1]
globals()
以字典类型返回当前位置的全部全局变量
语法:globals()
,无参数
返回值:以字典类型返回当前位置的全部全局变量,key对应变量名,value为变量的值
>>> x = 'test'
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': <module 'math' from '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/math.cpython-38-darwin.so'>, 'seasons': ['Spring', 'Summer', 'Fall', 'Winter'], 'd': 'Winter', 'i': 2, 'x': 'test', 'res': None, 'is_odd': <function is_odd at 0x7fd4e945fb80>, 'People': <class '__main__.People'>, 'p': <__main__.People object at 0x7fd4e9368bb0>}
hasattr()
判断对象是否有某属性
语法:hasattr(object, name)
,object-对象,name-属性的名字,需为字符串
返回值:如果对象有该属性,则返回True,否则返回False
>>> class People:
... sex = [0, 1]
...
>>> hasattr(People, 'sex')
True
hash()
获取一个对象的哈希值
语法:hash(object)
,object-字符串或者数值对象,若要应用于list、dict等,则需要转换为字符串
返回值:该对象的哈希值(哈希值是一个固定大小的整数,用于标识对象的特定值)
>>> hash(3)
3
>>> hash('3')
8019394005187592594
>>> hash(3.0)
3
>>> x = [1, 2, 3]
>>> hash(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(str(x))
1352512768786042936
hex()
将指定数字转换为16进制数
语法:hex(num)
,num-一个整数
返回值:以0x开头的字符串
>>> hex(6)
'0x6'
>>> hex(12)
'0xc'
>>> hex(-6)
'-0x6'
id()
返回对象的内存地址
语法:id(object)
返回值:对象的内存地址
>>> id(3)
4429646560
>>> id('test')
140552423619248
>>> id([1, 2, 3])
140552444496704
isinstance()
判断一个对象是否为已知的类型
语法:isinstance(object, classinfo)
,object-对象,classinfo-类名、基本类型或它们组成的元组(isinstance考虑继承关系,会认为子类是父类的类型,而type不考虑继承关系)
返回值:若对象的类型为第二个参数的类型或在第二个参数的类型元组中,则返回True,否则返回False
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> isinstance(B(), A)
True
>>> isinstance('test', str)
True
>>> isinstance(2, (int, str))
True
issubclass()
判断参数一是否为参数二的子类
语法:issubclass(class, classinfo)
返回值:如果 class 是 classinfo 的子类返回 True,否则返回 False。
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> issubclass(B, A)
True
>>> issubclass(Exception, BaseException) # 在python中,Exception是BaseException的子类
True
iter()
接收一个可迭代/可调用对象,将其转换为迭代器
语法:iter(object[, sentinel])
,object-可迭代/可调用对象,sentinel-哨兵,可选参数,若传递此参数,则第一个参数需要为可调用对象,在调用第一个参数对象时,若返回的值与 哨兵 的值相同,则迭代停止,抛出StopIteration异常
- 迭代器:可以被next()调用并不断返回下一个值的对象称为迭代器;
- 用法一:
iter(object)
,object为可迭代对象,将object对应的可迭代对象转换为迭代器,可被next()调用;
>>> p = [1, 2, 3, 4]
>>> m = iter(p)
>>> next(m)
1
>>> next(m)
2
>>> next(m)
3
>>> next(m)
4
>>> next(m)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
- 用法二:
iter(object, sentinel)
,object为可调用对象,sentinel为 哨兵(即标记结束的值),使用next()不断调用此迭代器,遇到哨兵值则结束;
>>> from random import randint
>>> def test():
... return randint(1, 10)
...
>>> x = iter(test, 3)
>>> next(x)
10
>>> next(x)
7
>>> next(x)
6
>>> next(x)
2
>>> next(x)
7
>>> next(x)
9
>>> next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> for i in iter(test, 3): # for循环的本质就是不断调用next()
... print(i)
...
8
10
2
5
7
7
9
6
5
9
2
10
返回值:迭代器对象
len()
返回对象的长度或元素个数
语法:len(object)
返回值:对象的长度或元素个数
>>> len('this is a test')
14
>>> len((1, 2, 3, 4, 5))
5
>>> len({'a': 1, 'b':2})
2
locals()
以字典类型返回当前位置的全部局部变量
语法:locals()
,无参数
返回值:当前位置的全部局部变量
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'test': <function test at 0x7fd268c5fc10>, 'x': <callable_iterator object at 0x7fd268b68910>, 'i': 10, 'randint': <bound method Random.randint of <random.Random object at 0x7fd26903c210>>, 'p': [1, 2, 3, 4], 'm': 'this is a test'}
map()
根据提供的函数对指定序列做映射
语法:map(function, iterable)
,function-函数,iterable-可迭代序列,将iterable的每个元素作为参数去调用function
返回值:返回一个迭代器,其中是每次调用function函数的返回值
>>> map(lambda x:x*2, 'abc')
<map object at 0x7fd268b68700>
>>> list(map(lambda x:x*2, 'abc'))
['aa', 'bb', 'cc']
>>> x = map(lambda x:x*2, 'abc')
>>> next(x)
'aa'
>>> next(x)
'bb'
>>> next(x)
'cc'
>>> next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> def twice(n):
... res = n * 2
... return res
...
>>> list(map(twice, [1, 2, 3]))
[2, 4, 6]
max()
返回给定参数的最大值
语法:max(x, y, z......[, key])
,参数为多个数字、字符串、序列,注意,用来比较的参数都需要为同一个类型,key-若指定该参数,则根据该参数来找到最大值,再返回此最大值对应的值
返回值:参数中的最大值
- 当参数为单个序列时,返回当前序列中的最大值;
- 当参数为多个序列时,按照索引从0开始挨个比较所有序列中的元素,找到最大值即返回其所在的序列;
>>> max(3, 8, 1, 9, 0, 2)
9
>>> max('d', 'x', 'e', 's')
'x'
>>> max([1, 2, 3, 4])
4
>>> max([1, 2], [7, 0])
[7, 0]
>>> max([1, 2], [2, 0])
[2, 0]
>>> d = {'a': 8, 'b':3, 'c':9, 'd':2}
>>> max(d, key=d.get) # 给序列中的key值,通过key=d.get进行计算,即每个key值计算了d.get(key),得到value,找到value中的最大值,再返回其对应的key
'c'
>>> t = ['1', '2', '-3', '-7']
>>> max(t, key=int) # 指定key后,会将序列中每个参数传递给key,通过key指定的函数/方法计算后,得出最大值,再返回此最大值对应的序列中过的值
'2'
min()
返回给定参数的最大值
语法:与max()
相同
返回值:参数中的最小值
next()
获取迭代器的下一个值
语法:next(iterable[, default])
,iterable-迭代器,default-可选参数,若设置此参数,当没有下一个元素时,就会返回此值,不设置则直接抛出StopIteration异常。
返回值:迭代器的下一个元素
>>> test = iter('abcd')
>>> next(test)
'a'
>>> next(test)
'b'
>>> next(test)
'c'
>>> next(test)
'd'
>>> next(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> test = iter('abcd')
>>> next(test, 'q')
'a'
>>> next(test, 'q')
'b'
>>> next(test, 'q')
'c'
>>> next(test, 'q')
'd'
>>> next(test, 'q')
'q'
oct()
将一个整数转换为一个8进制字符串
语法:oct(num)
,num-一个整数
返回值:该整数对应的 以0o开头的8进制字符串
>>> oct(12)
'0o14'
open()
打开一个文件并返回文件对象
语法:open(file, mode='r', buffering=-1, encoding=None)
,file-必需参数,文件路径,mode-可选参数,文件打开模式,默认为r,buffering-设置缓冲,encoding一般使用utf8
- 使用open函数打开文件后,一定要调用close()关闭文件对象,最好使用
with open(file, mode) as f
,with关键字会自动帮我们调用close来关闭文件对象; - mode常用参数的值如下
- x:写模式,新建一个文件,若文件已存在则会报错
- r:只读模式,文件指针会放在文件的开头
- w:只写模式,若文件已存在则打开文件,从文件开头开始编辑(删除文件原有内容),若文件不存在则自动创建新文件
- a:追加模式,若文件已存在,则从文件末尾开始写入(即文件指针放在文件末尾,不删除文件原有内容),若文件不存在则自动创建新文件
- b:以二进制格式打开文件,用于非文本文件
- +:打开一个文件进行更新,可读可写,该模式不能单独使用,需要和r、w配合使用
返回值:返回一个文件对象,可进行读写等操作
>>> with open('Desktop/test.txt', 'r+') as f:
... content = f.read()
...
>>> print(content)
test content
ord()
以一个字符为参数,返回其对应的ASCII或者Unicode数值
语法:ord(c)
,参数为一个字符
返回值:参数对应的ASCII或者Unicode数值
>>> ord('3')
51
>>> ord('z')
122
>>> ord('好')
22909
pow()
求x的y次方
语法:pow(x, y[, z])
,x和y为必选参数,z为可选参数
返回值:若只有x和y,则返回 xy,若有x、y、z,则返回 xy % z
>>> pow(2,2)
4
>>> pow(2,2,3)
1
print()
打印输出
语法:print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
,常用参数 objects-可为单个/多个,sep-输出多个对象时,使用此参数值来进行间隔,默认为空格,end-指定输出以什么结尾,默认为换行符,因此print输出后会默认换行
返回值:无返回值
>>> print(1)
1
>>> print(1, 2, 3)
1 2 3
>>> print(1, 2, 3, sep='/')
1/2/3
>>> print(1, 2, 3, end=',') # 修改了end参数,因此未换行,输出以,结尾
1 2 3,>>>
property()
在类中返回属性值
“在Python中,类有个封装原则,正常情况下,类的属性应该是隐藏的,我们只允许通过类提供的方法来间接实现对类的访问和操作。因此,在不破坏类封装原则的基础上,为了能够有效操作类中的属性,类中应包含读(或写)类属性的多个 getter(或 setter)方法,这样就可以通过“类对象.方法(参数)”的方式操作属性,而这样的操作可能会比较麻烦。“
因此Python提供了property()
函数,我们可以在类中封装了读、写、删除类属性的方法后,将这些方法作为参数传递给property()函数,property()函数会将这些属性返回,我们可以直接对此函数的返回值进行打印、赋值、删除。
语法:property(fget=None, fset=None, fdel=None, doc=None)
,fget-对应类的毒属性方法,fset-类的写属性方法,fdel-类的删除属性方法,doc-文档字符串,说明此函数的作用
返回值:类的属性
>>> class MyDog:
... def __init__(self, n):
... self._age = n
... def get_age(self):
... return self._age
... def set_age(self, m):
... self._age = m
... def del_age(self):
... del self._age
... dog = property(get_age, set_age, del_age, doc='对小狗的年龄进行读写删除')
...
>>> d = MyDog(3)
>>> d.dog
3
>>> d.dog = 5
>>> d.dog
5
>>> MyDog.dog.__doc__
'对小狗的年龄进行读写删除'
>>> del d.dog
>>> d.dog
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in get_age
AttributeError: 'MyDog' object has no attribute '_age'
其实一开始看菜鸟教程很懵逼,没看懂这个是用来干啥的,后来在 http://c.biancheng.net/view/2286.html 大概看明白了。
range()
生成一个整数序列对象
语法:range(start, stop[, step])
,start-序列开始值,可不写,默认为0,stop-序列结束值,到此值结束但不包括此值,step-步长,默认为1,若需要写此参数,则start和stop都必需写
返回值:整数序列的对象,可使用for循环进行迭代、可使用list转换为列表
>>> range(0, 5)
range(0, 5)
>>> list(range(0, 5))
[0, 1, 2, 3, 4]
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(0, 5, 2))
[0, 2, 4]
repr()
返回一个对象的字符串格式
语法:repr(object)
,object-对象
返回值:该对象的字符串格式
>>> repr(123)
'123'
>>> repr(['a', 'b', 'c'])
"['a', 'b', 'c']"
>>> d = {'runoob': 'runoob.com', 'google': 'google.com'}
>>> repr(d)
"{'runoob': 'runoob.com', 'google': 'google.com'}"
>>> len
<built-in function len>
>>> repr(len)
'<built-in function len>'
reversed()
返回一个反转的迭代器
语法:reversed(seq)
,seq-要转换的序列,可以为list、tuple、range、dict(会将key值进行反转并输出)、string
返回值:反转后的迭代器
>>> reversed('hello')
<reversed object at 0x7fe488534a60>
>>> list(reversed([1, 2, 3, 4]))
[4, 3, 2, 1]
>>> list(reversed(range(6)))
[5, 4, 3, 2, 1, 0]
>>> list(reversed({'a': 1, 'b': 2}))
['b', 'a']
round()
返回浮点数的四舍五入值
此函数精度不准确,不建议使用,具体在 Python保留小数的方法 中有详解。
语法:round(x[, n])
,x-数字,n-要保留的小数位数,默认为0
返回值:浮点数的四舍五入值
>>> round(3.47)
3
>>> round(3.14159, 3)
3.142
set()
创建一个无序不重复元素集
具体在 Python巩固基础02-基本数据类型之Set集合类型详解 中有详解
setattr()
用于设置属性值
语法:setattr(object, name, value)
,object-需要设置属性值的对象,name-属性的名称,需要为字符串,value-该属性的值,若该属性值不存在,则会创建并赋值
返回值:无
>>> class MyDog:
... age = 3
...
>>> d = MyDog()
>>> setattr(d, 'age', 5)
>>> d.age
5
>>> setattr(d, 'name', 'kai')
>>> d.name
'kai'
>>> MyDog.age
3
>>> MyDog.name # 只是给MyDog类的实例化对象d设置了name属性
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'MyDog' has no attribute 'name'
slice()
返回一个切片对象
语法:slice(start, stop[, step])
,start-切片起始位置,省略时默认为0,stop-切片结束位置,不包括stop,step-步长,默认为1
返回值:切片对象,将此切片对象传递给序列,可进行切片
>>> x = 'abcdefg'
>>> slice(0, 3)
slice(0, 3, None)
>>> q = slice(0, 3)
>>> x[q]
'abc'
>>> y = range(10)
>>> t = slice(0, 10, 2)
>>> y[t]
range(0, 10, 2)
>>> list(y[t])
[0, 2, 4, 6, 8]
>>> list(y)[0:10:2]
[0, 2, 4, 6, 8]
sorted()
对可迭代对象进行排序
语法:sorted(iterable, key=None, reverse=False)
,iterable-可迭代对象,key-用来进行比较的元素,可以将key指定为一个函数,把可迭代对象的元素作为入参,使用返回的结果来进行排序,reverse-排序方式,True为降序,False为升序,默认为False
返回值:返回一个新的经过排序后的list
- sort()是用于list进行排序的方法,list.sort(),并且此方法是在原list的基础上进行排序,会直接修改原list
- sorted()是作用于可迭代对象的函数,返回的是一个新的list,原可迭代对象不受影响
>>> a = [2, 3, 1, 9, -4, 0, -9]
>>> sorted(a)
[-9, -4, 0, 1, 2, 3, 9]
>>> sorted(a, key=abs) # 使用元素的绝对值来进行比较
[0, 1, 2, 3, -4, 9, -9]
>>> sorted(a, reverse=True) # 降序排序
[9, 3, 2, 1, 0, -4, -9]
>>> a # 原来的list不受影响
[2, 3, 1, 9, -4, 0, -9]
>>> a.sort()
>>> a # 使用list的sort方法,原来的a被直接修改
[-9, -4, 0, 1, 2, 3, 9]
staticmethod()
修饰类中的方法,声明其为静态方法
语法:在类中的静态方法上方加上 @staticmethod
返回值:无
- 在Python的类中,有 实例方法、类方法、静态方法三种
- 在实例方法中,第一个参数为 self,即为创建的实例本身,在创建类的实例对象时,Python解释器会默认把实例变量传递给实例方法,并且创建实例对象后,实例方法会与实例对象进行绑定
- 如果在方法中不需要访问任何实例方法和属性,可以独立于类单独存在,即也可以放在类之外作为一个独立的函数,这样的方法称为类的静态方法,而类的静态方法我们需要使用
@staticmethod
去进行修饰 - 类的静态方法可以不用创建实例,直接使用类进行调用;而类的实例方法则需要创建实例对象才可以通过实例对象调用
- 如果不用
@staticmethod
修饰静态方法,这样使用类的实例对象调用此方法时,Python解释器会传递self对象给静态方法,这样就会报错
>>> class A:
... def test(self):
... print('test')
... def static_method():
... print('this is a static method')
...
>>> A.static_method() # 可直接使用类去调用静态方法
this is a static method
>>> A.test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() missing 1 required positional argument: 'self'
>>> a = A()
>>> a.static_method() # 不用@staticmethod修饰静态方法,这样使用类的实例对象调用此方法时,Python解释器会传递self对象给静态方法
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: static_method() takes 0 positional arguments but 1 was given
>>> class A:
... @staticmethod
... def static_method():
... print('this is a static method')
... def test(self):
... print('test')
...
>>> a = A()
>>> a.static_method()
this is a static method
>>> A.static_method()
this is a static method
>>> A.test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() missing 1 required positional argument: 'self'
sum()
对序列进行求和计算
语法:sum(iterable[, start])
,iterable-需要求和的序列,start-指定求和的基数(菜鸟教程写的是指定相加的参数,但我感觉按照它的功能,写基数更合适一些),默认为0,作用为在对序列进行求和后,还会再加上此参数的值
返回值:对序列求和的结果
- sum函数的参数iterable,其中的元素需要是可相加的,sum函数不可进行字符串的拼接
- 因为start参数默认为0,因此不指定start参数时,序列中的元素都需要为int类型
- sum函数还可以用于列表的求和(相当于展开),此时需要将start参数也修改为列表类型
>>> sum([1, 2, 3])
6
>>> sum([1, 2, 3], -2)
4
>>> sum([[1, 2], [3, 4]], [5, 6]) # iterable参数为[ [1, 2], [3, 4] ],start参数为[5, 6]
[5, 6, 1, 2, 3, 4]
>>> sum([[1, 2], [3, 4]], [])
[1, 2, 3, 4]
super()
调用父类的方法
语法:super(type[, object-or-type])
,type-类,object-or-type - 类,一般是self,调用第一个参数的父类
返回值:无
- 在Python中,类的属性
__mro__
可以获取类的继承顺序,它返回一个tuple,Python按照此顺序,一级一级进行查找,保证父类的函数只调用一次 super()
,是从第一个参数类的上一级开始查找- 在Python3中,可省略super的参数,省略时默认为调用当前类的父类
class A(object):
def __init__(self):
print("class ---- A ----")
class B(A):
def __init__(self):
print("class ---- B ----")
super(B, self).__init__()
class C(A):
def __init__(self):
print("class ---- C ----")
super(C, self).__init__()
class D(B, C):
def __init__(self):
print("class ---- D ----")
super().__init__()
d = D()
print(D.__mro__)
----------
class ---- D ----
class ---- B ----
class ---- C ----
class ---- A ----
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
在此多重继承的例子中:D调用了super,按照__mro__
的顺序:调用B的init--调用C的init--最后再调用A的init
class A(object):
def __init__(self):
print("class ---- A ----")
class B(A):
def __init__(self):
print("class ---- B ----")
super(B, self).__init__()
class C(A):
def __init__(self):
print("class ---- C ----")
super(C, self).__init__()
class D(B, C):
def __init__(self):
print("class ---- D ----")
super(B, self).__init__() # 此处做了修改
d = D()
print(D.__mro__)
----------
class ---- D ----
class ---- C ----
class ---- A ----
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
在此例子中,D调用了super(B, self),按照__mro__
的顺序,从B类的上一级开始查找:调用C的init--再调用A的init
有一篇文章讲的挺好,在此记录一下:https://blog.csdn.net/wanzew/article/details/106993425
type()
返回对象的类型 或 返回一个新的类
语法:
type(object)
,object-对象,返回此对象的类型type(name, bases, dict)
,name-类的名称,bases-基类的元组,表示我们创建的是什么类型,dict-字典,类内定义的命名空间变量
>>> type('this')
<class 'str'>
>>> K = type('K', (object,), dict(age=5))
>>> k = K()
>>> k.age
5
vars()
返回对象的属性和属性值的字典对象
语法:vars([object])
,参数忽略时,即打印当前位置的属性和属性值
返回值:object的属性和属性值的字典对象
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 'abcdefg', 'q': slice(0, 3, None), 'y': range(0, 10), 't': slice(0, 10, 2), 'a': <__main__.A object at 0x7f8c7ed34b20>, 'A': <class '__main__.A'>, 'X': <class '__main__.X'>, 'b': <class '__main__.A'>, 'Y': <class '__main__.M'>, 'K': <class '__main__.K'>, 'k': <__main__.K object at 0x7f8c7ed34d00>}
>>> vars(K)
mappingproxy({'age': 5, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'K' objects>, '__weakref__': <attribute '__weakref__' of 'K' objects>, '__doc__': None})
>>> vars(A)
mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
>>> print(vars(K))
{'age': 5, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'K' objects>, '__weakref__': <attribute '__weakref__' of 'K' objects>, '__doc__': None}
mappingproxy:不可变映射类型
zip()
将多个可迭代对象的元素打包成元组
语法:zip([iterable, iterable, ......])
,参数可忽略
返回值:返回打包后的对象,可使用list进行转换,若忽略参数,则转换为list后是空列表
- 如果各个可迭代对象的元素个数不一致,则按照元素最少的个数来进行打包
- 可以使用
*
,将元组解压为列表
>>> list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9, 10])) # 打包成元组
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> a, b, c = zip(*zip([1, 2, 3], [4, 5, 6], [7, 8, 9, 10])) # 将打包后的zip对象 (1, 4, 7), (2, 5, 8), (3, 6, 9) 解压为列表并返回,感觉很像套娃
>>> a, b, c
((1, 2, 3), (4, 5, 6), (7, 8, 9))