python内置函数

第一类:数学运算,共7个

1、abs(x)

返回数字的绝对值。参数可以是整数或浮点数。如果参数是复数,则返回其大小 

 1 >>> abs(1)
 2 1
 3 >>> abs(0)
 4 0
 5 >>> abs(-1)
 6 1
 7 >>> abs(1.2)
 8 1.2
 9 >>> abs(-1.2)
10 1.2
View Code

2、divmod(ab)

1. 接受两个数值(非复数),返回两个数值的相除得到的商,和余数组成的元组。

2. 如果参数都是整数,执行的是floor除法,相当于 (a//b,a%b)。

>>> divmod(5,2)
(2, 1)
>>> 5//2
2
>>> 5%2
1

3. 如果参数时浮点数,相当于( math.floor(a/b),a%b

>> divmod(5.5,2)
(2.0, 1.5)
>>> math.floor(5.5/2)
2
>>> 5.5/2
2.75
>>> math.floor(5.5/2.0)
2
>>> 5.5%2
1.5

3、 

max(iterable*[, keydefault])

max(arg1arg2*args[, key])

3.1. 函数功能为取传入的多个参数中的最大值,或者传入的可迭代对象元素中的最大值
默认数值型参数,取值大者;
字符型参数,取字母表排序靠后者。
还可以传入命名参数key,其为一个函数,用来指定取最大值的方法。default命名参数用来指定最大值不存在时返回的默认值。

3.2. 函数至少传入两个参数,但是有只传入一个参数的例外,此时参数必须为可迭代对象,返回的是可迭代对象中的最大元素。

>>> max(1)             # 传入1个参数报错
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    max(1)
TypeError: 'int' object is not iterable
>>> max(1,2)           # 传入2个参数 取2个中较大者
2
>>> max(1,2,3)          # 传入3个参数 取3个中较大者
3
>>> max('1234')         # 传入1个可迭代对象,取其最大元素值
'4'

3.3. 当传入参数为数据类型不一致时,传入的所有参数将进行隐式数据类型转换后再比较,如果不能进行隐式数据类型转换,则会报错

>>> max(1,1.1,1.3E1)          # 整数与浮点数可取最大值
13.0
>>> max(1,2,3,'3')           # 数值与字符串不能取最大值
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    max(1,2,3,'3')
TypeError: unorderable types: str() > int()

>>> max([1,2],[1,3])         # 列表与列表可取最大值
[1, 3]
>>> max([1,2],(1,3))         # 列表与元组不能取最大值
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    max([1,2],(1,3))
TypeError: unorderable types: tuple() > list()

3.4. 当存在多个相同的最大值时,返回的是最先出现的那个最大值。

#定义a、b、c 3个列表
>>> a = [1,2]
>>> b = [1,1]
>>> c = [1,2]

#查看a、b、c 的id
>>> id(a)
>>> id(b)
>>> id(c)

#取最大值
>>> d = max(a,b,c)
>>> id(d)

#验证是否最大值是否是a
>>> id(a) == id(d)
True

3.5. 默认数值型参数,取值大者;
字符型参数,取字母表排序靠后者;
序列型参数,则依次按索引位置的值进行比较取最大者。还可以通过传入命名参数key,指定取最大值方法。

>>> max(1,2)          # 取数值大者
>>> max('a','b')       # 取排序靠后者
'b'
>>> max('ab','ac','ad')   # 依次按索引比较取较大者
'ad'

>>> max(-1,0)         # 数值默认去数值较大者
>>> max(-1,0,key = abs)   # 传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1

3.6. key参数的另外一个作用是,不同类型对象本来不能比较取最大值的,传入适当的key函数,将所有参数转为同类型,变得可以比较能取最大值了。

>>> max(1,2,'3')           #数值和字符串不能取最大值
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    max(1,2,'3')
TypeError: unorderable types: str() > int() 
>>> max(1,2,'3',key = int)     # 指定key为转换函数后,可以取最大值
'3'

>>> max((1,2),[1,1])                 #元组和列表不能取最大值
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    max((1,2),[1,1])
TypeError: unorderable types: list() > tuple()
>>> max((1,2),[1,1],key = lambda x : x[1])   #指定key为返回序列索引1位置的元素后,可以取最大值
(1, 2)

3.7. 当只传入的一个可迭代对象时,而且可迭代对象为空,则必须指定命名参数default,用来指定最大值不存在时,函数返回的默认值

>>> max(())               #空可迭代对象不能取最大值
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    max(())
ValueError: max() arg is an empty sequence
>>> max((),default=0)         #空可迭代对象,指定default参数为默认值
>>> max((),0)              #默认值必须使用命名参数进行传参,否则将被认为是一个比较的元素
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    max((),0)
TypeError: unorderable types: int() > tuple()

4、

min(iterable*[, keydefault])

min(arg1arg2*args[, key])

4.1. 函数功能为取传入的多个参数中的最小值,或者传入的可迭代对象元素中的最小值。默认数值型参数,取值小者;字符型参数,取字母表排序靠前者。还可以传入命名参数key,其为一个函数,用来指定取最小值的方法。default命名参数用来指定最小值不存在时返回的默认值。功能与max函数相反。

4.2. 函数至少传入两个参数,但是有只传入一个参数的例外,此时参数必须为可迭代对象,返回的是可迭代对象中的最小元素

>>> min(1)             # 传入1个参数报错
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    min(1)
TypeError: 'int' object is not iterable
>>> min(1,2)           # 传入2个参数 取2个中较小者
>>> min(1,2,3)          # 传入3个参数 取3个中较小者
>>> min('1234')         # 传入1个可迭代对象,取其最小元素值
'1'

4.3. 当传入参数为数据类型不一致时,传入的所有参数将进行隐式数据类型转换后再比较,如果不能进行隐式数据类型转换,则会报错。

>>> min(1,1.1,1.3e1)       # 整数与浮点数可取最小值
>>> min(1,2,'3')          # 数值与字符串不能取最小值
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    min(1,2,'3')
TypeError: unorderable types: str() < int()

>>> min([1,2],[1,3])       # 列表与列表可取最小值
[1, 2]
>>> min((1,2),[1,3])       # 列表与元组不能取最小值
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    min((1,2),[1,3])
TypeError: unorderable types: list() < tuple()

4.4. 当存在多个相同的最小值时,返回的是最先出现的那个最小值

#定义a、b、c 3个列表
>>> a = [1,2]
>>> b = [1,3]
>>> c = [1,2]

#查看a、b、c 的id
>>> id(a)
>>> id(b)
>>> id(c)

#取最小值
>>> d = min(a,b,c)
>>> id(d)


#验证是否最小值是否是a
>>> id(a) == id(d)
True

4.5. 默认数值型参数,取值小者;
字符型参数,取字母表排序靠前者;
序列型参数,则依次按索引位置的值进行比较取最小者。还可以通过传入命名参数key,指定取最小值方法。

>>> min(1,2)            # 取数值小者
>>> min('a','b')         # 取排序靠前者
'a'
>>> min('ab','ac','ad')   # 依次按索引比较取较小者
'ab'

>>> min(-1,-2)         # 数值默认去数值较小者
-2
>>> min(-1,-2,key = abs)   # 传入了求绝对值函数,则参数都会进行求绝对值后再取较小者
-1

4.6. key参数的另外一个作用是,不同类型对象本来不能比较取最小值的,传入适当的key函数,使用key函数转换所有的参数为同一类型,变得可以比较能取最小值了。

>>> min(1,2,'3')         #数值和字符串不能取最小值
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    min(1,2,'3')
TypeError: unorderable types: str() < int()
>>> min(1,2,'3',key = int)   # 指定key为转换函数后,可以取最小值

>>> min([1,2],(1,1))       #元组和列表不能取最小值
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    min([1,2],(1,1))
TypeError: unorderable types: tuple() < list()
>>> min([1,2],(1,1),key = lambda x:x[1])     #指定key为返回序列索引1位置的元素后,可以取最小值
(1, 1)

4.7. 当只传入的一个可迭代对象时,而且可迭代对象为空,则必须指定命名参数default,用来指定最小值不存在时,函数返回的默认值

>>> min(())               #空可迭代对象不能取最小值
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    min(())
ValueError: min() arg is an empty sequence

>>> min((),default = 0)       #空可迭代对象,指定default参数为默认值

>>> min((),0)             #默认值必须使用命名参数进行传参,否则将被认为是一个比较的元素
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    min((),0)
TypeError: unorderable types: int() < tuple()

5、pow(xy[, z])

5.1. 函数有两个必需参数x,y和一个可选参数z,结果返回x的y次幂乘(相当于x**y),如果可选参数z有传入值,则返回幂乘之后再对z取模(相当于pow(x,y)%z)

>>> pow(2,3)
>>> 2**3

>>> pow(2,3,5)
>>> pow(2,3)%5

5.2. 所有的参数必须是数值类型。 

>>> pow('2',3)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    pow('2',3)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

5.3. 如果x,y有一个是浮点数,则结果将转换成浮点数 

>>> pow(2,0.1)
1.0717734625362931

5.4. 如果x,y都是整数,则结果也是整数,除非y是负数;如果y是负数,则结果返回的是浮点数,浮点数不能取模,所有可选参数z不能传入值。

>>> pow(10,2)
>>> pow(10,-2)
0.01
>>> pow(10,-2,3)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    pow(10,-2,3)
ValueError: pow() 2nd argument cannot be negative when 3rd argument specified

5.5. 如果可选参数z传入了值,x,y必须为整数,且y不能为负数(否则结果是浮点数,而浮点数不能进行取模运算)。

>>> pow(2,3,5)

>>> pow(10,0.1,3)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    pow(10,0.1,3)
TypeError: pow() 3rd argument not allowed unless all arguments are integers

>>> pow(10,-2,3)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    pow(10,-2,3)
ValueError: pow() 2nd argument cannot be negative when 3rd argument specified

6、round(number[, ndigits])

6.1. round函数用于对浮点数进行四舍五入求值,具体保留几位小数,以传入的ndigits参数来控制。

>>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149

6.2. ndigits参数为可选参数,当不传入时,即以默认保留0位小数进行取整,返回的是整数。

>>> round(1.1314926)
1

6.3. ndigits参数传入0时,虽然与不传入ndigits参数一样保留0位小数进行四舍五入,但是返回的值是浮点型

>>> round(1.1314926,0)
1.0

6.4. ndigits参数小于0时,对整数部分进行四舍五入,ndigits参数控制了对浮点数的整数部分的后几位进行四舍五入,小数部分全部清0,返回类型是浮点数。如果传入的浮点数的整数部分位数小于ndigits参数绝对值,则返回0.0.

>>> round(11314.926,-1)
11310.0
>>> round(11314.926,-3)
11000.0
>>> round(11314.926,-4)
10000.0
>>> round(11314.926,-5)
0.0

6.5. round四舍五入时是遵循靠近0原则,所以-0.5和0.5进行0位四舍五入,返回的都是0.

>>> round(0.5)
0
>>> round(-0.5)
0

6.6. 对于浮点数求四舍五入有一个陷阱,有些四舍五入结果不像预期那样,比如round(2.675,2) 的结果是2.67 而不是预期的 2.68,这不是bug,而是浮点数在存储的时候因为位数有限,实际存储的值和显示的值有一定误差

>>> round(2.675, 2)
2.67

6.7. 对整数也能进行round操作,返回值也是整形。

>>> round(1234567,0)
1234567
>>> round(1234567,-1)
1234570
>>> round(1234567,-2)
1234600
>>> round(1234567,-3)
1235000
>>> round(1234567,-4)
1230000
>>> round(1234567,-5)
1200000
>>> round(1234567,-6)
1000000
>>> round(1234567,-7)
0

7、sum(iterable[, start])

7.1. 函数功能是对可迭代类型进行求和。要求:① 接收对象是可迭代类型。② 可迭代对象所有元素类型是数值型。

# 传入可迭代对象
>>> sum((1,2,3,4))
>>> sum([1,2,3,4])
>>> sum(range(10))

# 元素类型必须是数值型
>>> sum((1.5,2.5,3.5,4.5))
12.0
>>> sum((complex(1,-1),complex(2,-2)))
(3-3j)

>>> sum((1,2,3,'4'))
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    sum((1,2,3,'4'))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

7.2. 可以传入一个可选参数start,表示求和前的初始化值,如果传入空的可迭代数据类型,则返回初始值。

>>> sum((1,2,3,4),2)
>>> sum((1,2,3,4),-10)

# 传入空可迭代对象,直接返回初始值
>>> sum([],2)

第二类:类型转换,共24个

1、class bool([x])

1. 返回值为True或者False的布尔值

2. 参数如果缺省,则返回False

>>> bool() #未传入参数
False

只要参数X,非0、非空、非None结果就是True,否则为False

2、class int(x=0) class int(x, base=10)

2.1. 不传入参数时,得到结果0。

>>> int()
0

2.2. 传入数值时,调用其__int__()方法,浮点数将向下取整。

>>> int(3)
3
>>> int(3.6)
3

2.3. 传入数字字符串时,默认以10进制进行转换。

>>> int('36')

>>> int('3.6')
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    int('3.6')
ValueError: invalid literal for int() with base 10: '3.6'

2.4. 字符串中允许包含"+"、"-"号,但是加减号与数值间不能有空格,数值后、符号前可出现空格。

>>> int('+36')
>>> int('-36')
-36
>>> int('   -36        ')
-36
>>> int(' - 36        ')
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    int(' - 36        ')
ValueError: invalid literal for int() with base 10: ' - 36

2.5. 传入字符串,并指定了进制,则按对应进制将字符串转换成10进制整数

>>> int('01',2)
>>> int('02',3)
>>> int('07',8)
>>> int('0f',16)

3、class float([x])

3.1. 函数功能将一个数值或者字符数字转换成浮点型数值。

>>> float(3)
3.0
>>> float('3')
3.0

3.2. 不提供参数的时候,返回0.0。

>>> float()
0.0

3.3. 字符串必须能正确转换成浮点型数值的,否则报错。

>>> float('3.14.15926')
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    float('3.14.15926')
ValueError: could not convert string to float: '3.14.15926'

3.4. 字符串中允许出现“+”、“-”两个符号,两个符号和数字之间不能出现空格,但是符号前面和数字后面允许出现空格。

>>> float('+3.14')       #带正号
3.14
>>> float('-3.14')       #带负号
-3.14
>>> float('  -3.14  ')     #正负号前、数字后可以有空格
-3.14
>>> float('- 3.14')       #正负号与数字间不可以有空格
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    float('- 3.14')
ValueError: could not convert string to float: '- 3.14'

3.5. 有几个特殊的字符串能正确转换,"Infinity"或者“inf”(不区分大小写),能正确转换,表示无穷大,可以和“+”、“-”一起使用;“nan”也能正确转换,表示没有值。

>>> float('Infinity')
inf
>>> float('inf')
inf

>>> float('inFinIty')     #不区分大小写
inf

>>> float('+inFinIty')     #正无穷
inf
>>> float('-inFinIty')     #负无穷
-inf

>>> float('nan')         #没有值
nan

3.6. 定义的对象如果要被float函数正确转换成浮点数,需要定义__float__函数。

>>> class X:
    def __init__(self,score):
        self.score = score

>>> x = X(9.7)
>>> float(x)               #不能转换
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    float(x)
TypeError: float() argument must be a string or a number, not 'X'


>>> class X:               #重新定义类,加入__float__方法
    def __init__(self,score):
        self.score = score
    def __float__(self):
        return self.score

>>> x = X(9.7)
>>> float(x)               #可以转换
9.7

4、class complex([real[, imag]])

4.1. 函数功能,返回一个复数。有两个可选参数。

4.2. 当两个参数都不提供时,返回复数 0j。

>>> complex()
0j

4.3. 当第一个参数为字符串时,调用时不能提供第二个参数。此时字符串参数,需是一个能表示复数的字符串,而且加号或者减号左右不能出现空格。

>>> complex('1+2j',2)         #第一个参数为字符串,不能接受第二个参数
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    complex('1+2j',2)
TypeError: complex() can't take second arg if first is a string

>>> complex('1 + 2j')         #不能有空格
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    complex('1 + 2j')
ValueError: complex() arg is a malformed string

4.4. 当第一个参数为int或者float时,第二个参数可为空,表示虚部为0;如果提供第二个参数,第二个参数也需为int或者float。

>>> complex(2)
(2+0j)
>>> complex(2.1,-3.4)
(2.1-3.4j)

5、

class str(object=''

class str(object=b''encoding='utf-8'errors='strict')

5.1. str函数功能时将对象转换成其字符串表现形式,如果不传入参数,将返回空字符串。

>>> str()
''
>>> str(None)
'None'
>>> str('abc')
'abc'
>>> str(123)
'123'

5.2. 当转换二进制流时,可以传入参数encoding,表示读取字节数组所使用的编码格式;参数errors,表示读取二进制的错误级别。

>>> file = open('test.txt','rb')         # 打开文件
>>> fileBytes = file.read()             # 读取二进制流
>>> fileBytes
b'xe6x88x91xe6x98xafxe7xacxac1xe8xa1x8cxe6x96x87xe6x9cxacxefxbcx8cxe6x88x91xe5xb0x86xe8xa2xabxe6x98xbexe7xa4xbaxe5x9cxa8xe5xb1x8fxe5xb9x95
xe6x88x91xe6x98xafxe7xacxac2xe8xa1x8cxe6x96x87xe6x9cxacxefxbcx8cxe6x88x91xe5xb0x86xe8xa2xabxe6x98xbexe7xa4xbaxe5x9cxa8xe5xb1x8fxe5xb9x95
xe6x88x91xe6x98xafxe7xacxac3xe8xa1x8cxe6x96x87xe6x9cxacxefxbcx8crxe6x88x91xe5xb0x86xe8xa2xabxe6x98xbexe7xa4xbaxe5x9cxa8xe5xb1x8fxe5xb9x95'
>>> str(fileBytes)                  # 默认将二进制流转换成字符串表现形式
"b'\xe6\x88\x91\xe6\x98\xaf\xe7\xac\xac1\xe8\xa1\x8c\xe6\x96\x87\xe6\x9c\xac\xef\xbc\x8c\xe6\x88\x91\xe5\xb0\x86\xe8\xa2\xab\xe6\x98\xbe\xe7\xa4\xba\xe5\x9c\xa8\xe5\xb1\x8f\xe5\xb9\x95\r\n\xe6\x88\x91\xe6\x98\xaf\xe7\xac\xac2\xe8\xa1\x8c\xe6\x96\x87\xe6\x9c\xac\xef\xbc\x8c\xe6\x88\x91\xe5\xb0\x86\xe8\xa2\xab\xe6\x98\xbe\xe7\xa4\xba\xe5\x9c\xa8\xe5\xb1\x8f\xe5\xb9\x95\r\n\xe6\x88\x91\xe6\x98\xaf\xe7\xac\xac3\xe8\xa1\x8c\xe6\x96\x87\xe6\x9c\xac\xef\xbc\x8cr\xe6\x88\x91\xe5\xb0\x86\xe8\xa2\xab\xe6\x98\xbe\xe7\xa4\xba\xe5\x9c\xa8\xe5\xb1\x8f\xe5\xb9\x95'"
>>> str(fileBytes,'utf-8')             # 传入encoding参数,函数将以此编码读取二进制流的内容
'我是第1行文本,我将被显示在屏幕
我是第2行文本,我将被显示在屏幕
我是第3行文本,r我将被显示在屏幕'
>>> str(fileBytes,'gbk')               # 当传入encoding不能解码时,会报错(即errors参数默认为strict)
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    str(fileBytes,'gbk')
UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 8: illegal multibyte sequence
>>> str(fileBytes,'gbk','ignore') # 'ignore' 忽略级别,字符编码有错,忽略掉.
'鎴戞槸绗1琛屾枃鏈锛屾垜灏嗚鏄剧ず鍦ㄥ睆骞
鎴戞槸绗2琛屾枃鏈锛屾垜灏嗚鏄剧ず鍦ㄥ睆骞
鎴戞槸绗3琛屾枃鏈锛宺鎴戝皢琚鏄剧ず鍦ㄥ睆骞'
>>> str(fileBytes,'gbk','replace') # 'replace' 替换级别,字符编码有错的,替换成?. 
'鎴戞槸绗�1琛屾枃鏈�锛屾垜灏嗚��鏄剧ず鍦ㄥ睆骞�
鎴戞槸绗�2琛屾枃鏈�锛屾垜灏嗚��鏄剧ず鍦ㄥ睆骞�
鎴戞槸绗�3琛屾枃鏈�锛宺鎴戝皢琚�鏄剧ず鍦ㄥ睆骞�'

6.class bytearray([source[, encoding[, errors]]])

 6.1. 返回值为一个新的字节数组

 6.2. 当3个参数都不传的时候,返回长度为0的字节数组

>>> b = bytearray()
>>> b
bytearray(b'')
>>> len(b)
0

6.3. 当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组

>>> bytearray('中文')
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    bytearray('中文')
TypeError: string argument without an encoding
>>> bytearray('中文','utf-8')
bytearray(b'xe4xb8xadxe6x96x87')

6.4. 当source参数为整数时,返回这个整数所指定长度的空字节数组

>>> bytearray(2)
bytearray(b'x00x00')
>>> bytearray(-2)                   #整数需大于0,使用来做数组长度的
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    bytearray(-2)
ValueError: negative count

6.5. 当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回

6. 6. 当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里

>>> bytearray([1,2,3])
bytearray(b'x01x02x03')
>>> bytearray([256,2,3])                 #不在0-255范围内报错
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    bytearray([256,2,3])
ValueError: byte must be in range(0, 256)

7. class bytes([source[, encoding[, errors]]])

7.1. 返回值为一个新的不可修改字节数组,每个数字元素都必须在0 - 255范围内,和bytearray函数的具有相同的行为,差别仅仅是返回的字节数组不可修改

7.2. 当3个参数都不传的时候,返回长度为0的字节数组

>>> b = bytes()
>>> b
b''
>>> len(b)
0

7.3. 当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组

>>> bytes('中文')             #需传入编码格式
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    bytes('中文')
TypeError: string argument without an encoding
>>> bytes('中文','utf-8')
b'xe4xb8xadxe6x96x87'
>>> '中文'.encode('utf-8')
b'xe4xb8xadxe6x96x87'

7.4. 当source参数为整数时,返回这个整数所指定长度的空字节数组

>>> bytes(2)
b'x00x00'
>>> bytes(-2)                   #整数需大于0,用于做数组长度
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    bytes(-2)
ValueError: negative count

7.5. 当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回

7.6. 当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里

>>> bytes([1,2,3])
b'x01x02x03'
>>> bytes([256,2,3])
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    bytes([256,2,3])
ValueError: bytes must be in range(0, 256)

7.7. 返回数组不可修改

>>> b = bytes(10)
>>> b
b'x00x00x00x00x00x00x00x00x00x00'
>>> b[0]
>>> b[1] = 1           #不可修改
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    b[1] = 1
TypeError: 'bytes' object does not support item assignment

>>> b = bytearray(10)
>>> b
bytearray(b'x00x00x00x00x00x00x00x00x00x00')
>>> b[1] = 1           #可修改
>>> b
bytearray(b'x00x01x00x00x00x00x00x00x00x00')

 8、class memoryview(obj)

8.1. 函数功能返回内存查看对象,实际上是内存查看对象(Momory view)的构造函数。

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

8.3. Python内置对象中支持缓冲区协议的对象有bytes和bytearray。

>>> v = memoryview(b'abcefg')
>>> v[1]
>>> v[-1]
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'

9、ord(c)

9.1. 函数功能传入一个Unicode 字符,返回其对应的整数数值

>>> ord('a')
97
>>> ord('@')
64

9.2. 其功能和chr函数刚好相反。 

>>> chr(97)
'a'
>>> chr(64)
'@'

 10、chr(i)

10.1. 函数返回整形参数值所对应的Unicode字符的字符串表示

>>> chr(97)         #参数类型为整数
'a'

>>> chr('97')       #参数传入字符串时报错
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    chr('97')
TypeError: an integer is required (got type str)

>>> type(chr(97))     #返回类型为字符串
<class 'str'>

10.2. 它的功能与ord函数刚好相反

>>> chr(97)
'a'
>>> ord('a')
97

10.3. 传入的参数值范围必须在0-1114111(十六进制为0x10FFFF)之间,否则将报ValueError错误

>>> chr(-1) #小于0报错
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    chr(-1)
ValueError: chr() arg not in range(0x110000)

>>> chr(1114111)
'U0010ffff'

>>> chr(1114112) #超过1114111报错
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    chr(1114112)
ValueError: chr() arg not in range(0x110000)

11、bin(x)

11.1. 将一个整形数字转换成二进制字符串 

>>> b = bin(3) 
>>> b
'0b11'
>>> type(b)           #获取b的类型
<class 'str'>

11. 2. 如果参数x不是一个整数,则x必须定义一个 __index__() 方法,并且方法返回值必须是整数。

    11.2.1 如果对象不是整数,则报错

>>> class A:
    pass

>>> a = A()
>>> bin(a) 
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    bin(a)
TypeError: 'A' object cannot be interpreted as an integer

11.2.2 如果对象定义了__index__方法,但返回值不是整数,报错

>>> class B:
    def __index__(self):
        return "3"

>>> b = B()
>>> bin(b)
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    bin(b)
TypeError: __index__ returned non-int (type str)

11.2.3 对象定义了__index__方法,且返回值是整数,将__index__方法返回值转换成二进制字符串

>>> class C:
    def __index__(self):
        return 3

>>> c = C()
>>> bin(c)
'0b11'

12、oct(x)

12.1. 函数功能将一个整数转换成8进制字符串。如果传入浮点数或者字符串均会报错。

>>> a = oct(10)

>>> a
'0o12'
>>> type(a)         # 返回结果类型是字符串
<class 'str'>

>>> oct(10.0)        # 浮点数不能转换成8进制
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    oct(10.0)
TypeError: 'float' object cannot be interpreted as an integer

>>> oct('10')       # 字符串不能转换成8进制
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    oct('10')
TypeError: 'str' object cannot be interpreted as an integer

12.2. 如果传入参数不是整数,则其必须是一个定义了__index__并返回整数函数的类的实例对象。

# 未定义__index__函数,不能转换
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age

        
>>> a = Student('Kim',10)
>>> oct(a)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    oct(a)
TypeError: 'Student' object cannot be interpreted as an integer

# 定义了__index__函数,但是返回值不是int类型,不能转换
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __index__(self):
        return self.name

>>> a = Student('Kim',10)
>>> oct(a)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    oct(a)
TypeError: __index__ returned non-int (type str)

# 定义了__index__函数,而且返回值是int类型,能转换
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __index__(self):
        return self.age

>>> a = Student('Kim',10)
>>> oct(a)
'0o12'

13、hex(x)

13.1. 函数功能将10进制整数转换成16进制整数。

>>> hex(15)
'0xf'
>>> hex(16)
'0x10'

13.2. 如果参数x不是整数,则它必须定义一个返回整数的__index__函数

# 未定义__index__函数
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age

>>> 
>>> s = Student('Kim',10)
>>> hex(s)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    hex(s)
TypeError: 'Student' object cannot be interpreted as an integer

# 定义__index__函数,但是返回字符串
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __index__(self):
        return self.name

>>> s = Student('Kim',10)
>>> hex(s)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    hex(s)
TypeError: __index__ returned non-int (type str)

# 定义__index__函数,并返回整数
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __index__(self):
        return self.age

>>> s = Student('Kim',10)
>>> hex(s)
'0xa'

14、class tuple(object)

14.1. 函数功能创建一个新的元组。

14.2. 不传入任何参数函数将创建一个空的元组。

#不传入参数,创建空元组
>>> tuple() 
()

14.3. 函数可以接收1个可迭代对象作为参数,将使用可迭代对象的每个元素创建一个新的元组。

#传入不可迭代对象,不能创建新的元组
>>> tuple(121)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    tuple(121)
TypeError: 'int' object is not iterable

#传入可迭代对象。使用其元素创建新的元组
>>> tuple('121')
('1', '2', '1')
>>> tuple([1,2,1])
(1, 2, 1)
>>> tuple((1,2,1))
(1, 2, 1)

14.4. 创建新的元组还可以使用一对括号的方式:

14.4.1 使用一对括号来创建空的元组。

>>> a= ()
>>> a
()

14.4.2 创建单个元素的元组时必须尾随逗号

>>> a = (1,)
>>> a #a是元组
(1,)
>>> a = (1)
>>> a #a是数值

14.4.3 创建多个元素的元组,依次用逗号隔开。

>>> a = (1,2,3)
>>> a
(1, 2, 3)

15、class list([iterable])

15.1. list函数,实际是上列表类型的构造函数。

15.2. 可以不传入任何参数,结果返回一个空列表。

>>> a = list()
>>> a
[]

15.3. 可以传入一个可迭代对象,如字符串,字节数组、元组、列表、range对象,结果将返回可迭代对象中元素组成的列表。

>>> list('abcd')           # 字符串
['a', 'b', 'c', 'd']
>>> list(bytes('abcd','utf-8'))   # 字节数组
[97, 98, 99, 100]
>>> list(('a','b','c','d'))     # 元组
['a', 'b', 'c', 'd']
>>> list(['a','b','c','d'])     # 列表
['a', 'b', 'c', 'd']
>>> list(range(1,5))         # range对象
[1, 2, 3, 4]

16、

class dict(**kwarg)

class dict(mapping**kwarg)

class dict(iterable**kwarg)

16.1. 字典类的构造函数。

16.2. 不传入任何参数时,返回空字典

>>> dict()
{}

16.3. 可以传入键值对创建字典

>>> dict(a = 1)
{'a': 1}
>>> dict(a = 1,b = 2)
{'b': 2, 'a': 1}

16.4. 可以传入映射函数创建字典。

>>> dict(zip(['a','b'],[1,2]))
{'b': 2, 'a': 1}

16.5. 可以传入可迭代对象创建字典

>>> dict((('a',1),('b',2)))
{'b': 2, 'a': 1}

 17、class set([iterable])

17.1.  传入一个可迭代对象,生成一个新的集合

>>> a = set(range(10))
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

17.2.  不传入参数时,生成一个新的空集合

>>> a = set()
>>> a
set()

17.3. 返回的集合是可以修改的。

>>> a = set()
>>> a
set()
>>> a.add(1)
>>> a
{1}

18、class frozenset([iterable])

18.1. 传入一个可迭代对象,生成一个新的不可变集合。

>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
>>> b = frozenset('I am a Pythoner')
>>> b
frozenset({'y', 'I', ' ', 'r', 't', 'm', 'h', 'o', 'a', 'e', 'n', 'P'})

18.2. 不传入参数时,生成的空的不可变集合。

>>> c = frozenset()
>>> c
frozenset()

19、enumerate(iterable, start=0)

1. 接受一个可迭代对象(序列或者迭代器),返回一个可枚举对象(同时返回索引和值,其中索引可以指定起始值)。

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) #指定起始值
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

20、

range(stop)

range(startstop[, step])

20.1. range函数用于生成一个range对象,range类型是一个表示整数范围的类型。  

20.2. 可以直接传入一个结束整数来初始化一个range类型,默认起始值为0(包含0).结束整数可以大于0,也可以小于等于0,但是小于等于0的时候生成的range对象实际是不包含任何元素的。

>>> a = range(5)
>>> a
range(0, 5)
>>> len(a)
>>> for x in a:print(x)
1
3

>>> b = range(0)         # 传入0,空range对象
>>> len(b)

>>> c = range(-5)          # 传入负数,空range对象
>>> len(c)

20.3. 可以传入一个起始整数和一个结束整数来初始化一个range类型,生成的range类型包含起始整数(包含),和结束整数(不包含)之间的所有整数。

>>> a = range(1,5)
>>> a
range(1, 5)
>>> for x in a:print(x)
2
4

20.4. 传入了起始整数和结束整数,还可以同时传入一个步进值来初始化一个range类型,生成的range类型包含起始整数(包含),和结束整数(不包含)之间的以步进值筛选后的整数

>>> a = range(1,10,3)
>>> a
range(1, 10, 3)
>>> for x in a:print(x)
4

20.5. 初始化range类型时起始整数和结束整数,遵循的是左臂右开原则,即包含起始整数,但不包含结束整数。

>>> a = range(1,5)
>>> a
range(1, 5) 
>>> for x in a:print(x) # 包含1,不包含5
2
4

20.6. range接收的参数都必须是整数,不能是浮点数等其它数据类型

>>> a = range(3.5)
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    a = range(3.5)
TypeError: 'float' object cannot be interpreted as an integer
>>> a = range('3.5')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    a = range('3.5')
TypeError: 'str' object cannot be interpreted as an integer

20.7. range实际上是一个不可变的序列类型,可以对它进行取元素、切片等序列操作,但是不能对其中元素修改值。

>>> a = range(1,5)

>>> a[0] # 取元素
>>> a[:-2] # 切片
range(1, 3)
>>> a[1] = 2 # 修改元素值
Traceback (most recent call last):
  File "<pyshell#38>", line 1, in <module>
    a[1] = 2
TypeError: 'range' object does not support item assignment

21、iter(object[, sentinel])

21.1. 函数功能返回一个迭代器对象。

21.2. 当第二个参数不提供时,第一个参数必须是一个支持可迭代协议(即实现了__iter__()方法)的集合(字典、集合、不可变集合),或者支持序列协议(即实现了__getitem__()方法,方法接收一个从0开始的整数参数)的序列(元组、列表、字符串),否则将报错。

>>> a = iter({'A':1,'B':2}) #字典集合
>>> a
<dict_keyiterator object at 0x03FB8A50>
>>> next(a)
'A'
>>> next(a)
'B'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    next(a)
StopIteration
 
>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    next(a)
StopIteration

21.3. 当第二个参数sentinel提供时,第一个参数必须是一个可被调用对象。创建的迭代对象,在调用__next__方法的时候会调用这个可被调用对象,当返回值和sentinel值相等时,将抛出StopIteration异常, 终止迭代。

# 定义类
>>> class IterTest: 
    def __init__(self):
        self.start = 0
        self.end = 10
    def get_next_value(self):
        current = self.start
        if current < self.end:
            self.start += 1
        else:
            raise StopIteration
        return current

>>> iterTest = IterTest() #实例化类
>>> a = iter(iterTest.get_next_value,4) # iterTest.get_next_value为可调用对象,sentinel值为4
>>> a
<callable_iterator object at 0x03078D30>
>>> next(a)
>>> next(a)
>>> next(a)
>>> next(a)
>>> next(a) #迭代到4终止
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    next(a)
StopIteration

 22、

class slice(stop)

class slice(startstop[, step])

22.1. 函数实际上是一个切片类的构造函数,返回一个切片对象

22.2. 切片对象由3个属性start、stop、step组成,start和step默认值为None。切片对象主要用于对序列对象进行切片取对应元素。

>>> help(slice)
class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
 |  
 |  Methods defined here:
 |  
 |  ...#省略#
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  start
 |  
 |  step
 |  
 |  stop
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> a[None:5:None] # start step显式为None
[0, 1, 2, 3, 4]
>>> a[:5:] # start step默认为None
[0, 1, 2, 3, 4]
>>> a[2:5:None] # step显式为None
[2, 3, 4]
>>> a[2:5:] # step默认为None
[2, 3, 4]
>>> a[1:10:3]
[1, 4, 7]

22.3. 对应切片对象的3个属性start、stop、step,slice函数也有3个对应的参数start、stop、step,其值分别会付给切片对象的start、stop、step。

>>> c1 = slice(5)           # 定义c1
>>> c1
slice(None, 5, None)
>>> c2 = slice(2,5)         # 定义c2
>>> c2
slice(2, 5, None)
>>> c3 = slice(1,10,3)         # 定义c3
>>> c3
slice(1, 10, 3)
>>> a[c1]               # 和a[:5:]结果相同
[0, 1, 2, 3, 4]
>>> a[c2]               # 和a[2:5:]结果相同
[2, 3, 4]
>>> a[c3]               # 和a[1:10:3]结果相同
[1, 4, 7]

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

23.1. super函数返回的是一个代理对象,通过此对象可以调用所在类的父类或者兄弟类的方法,而不显示的指定父类或者兄弟类的类名。

23.2. 为什么要有super?

最早之前,在子类(B)中调用父类(A)的方法采用的方式如下: 

#定义父类A
>>> class A(object):
    def __init__(self):
        print('A.__init__')

#实例化A        
>>> a = A() 
A.__init__

# 定义子类B,继承A,在B的__init__ 方法中调用A的__init__方法
>>> class B(A): 
    def __init__(self):
        print('B.__init__')
        A.__init__(self)

 #实例化B
>>> b = B()
B.__init__
A.__init__

假设现在要更改新定义一个类(A1),并更改继承关系(B->A改成B->A1),则需要所有类中做如下修改:

#定义新的父类A1
>>> class A1(object):
    def __init__(self):
        print('A1.__init__')

#更改继承关系B->A改成B->A1
>>> class B(A1):
    def __init__(self):
        print('B.__init__')
        A1.__init__(self)

#能正确调用新的父类A1的__init__方法
>>> b = B()
B.__init__
A1.__init__

#假设忘了修改A.__init__(self)
>>> class B(A1):
    def __init__(self):
        print('B.__init__')
        A.__init__(self)
      
#则还是调用了A的__init__方法
>>> b = B()
B.__init__
A.__init__

引入super之后,不需要显示指定父类的类名,增强了程序的可维护性:

#B->A 改用super方式调用父类方法
>>> class B(A):
    def __init__(self):
        print('B.__init__')
        super().__init__()

#能正确调用父类方法
>>> b = B()
B.__init__
A.__init__

#更改继承关系B->A改成B->A1,调用父类方法方式不用修改
>>> class B(A1):
    def __init__(self):
        print('B.__init__')
        super().__init__()

#也能正确调用父类方法
>>> b = B()
B.__init__
A1.__init__

23.3. 不带任何参数的super等效于super(类名,self),此种情况多用于单继承关系的子类中。

#super不带参数
>>> class B(A1):
    def __init__(self):
        print('B.__init__')
        super().__init__()

#能正确调用父类方法
>>> b = B()
B.__init__
A1.__init__

#super带两个参数(类名,self)
>>> class B(A1):
    def __init__(self):
        print('B.__init__')
        super(B,self).__init__()

#也能正确调用父类方法
>>> b = B()
B.__init__
A1.__init__

23.4. 如果第2个参数不传入,则表示代理对象不绑定继承关系。

#super第2个参数不传入,生成代理对象不绑定继承关系
>>> class B(A1):
    def __init__(self):
        print('B.__init__')
        super(B).__init__()

#super(B).__init__()方法执行时不会调用父类方法
>>> b = B()
B.__init__

23.5. 如果第2个参数是一个对象,则对象必须是第1个参数指定类型的实例,此种关系多用于多层继承关系的子类中。

#定义父类A
>>> class A(object):
    def __init__(self):
        print('A.__init__')

#定义子类B,继承A,__init__中调用父类的__init__方法
>>> class B(A):
    def __init__(self):
        print('B.__init__')
        super().__init__()

#定义子类C,继承B,__init__中调用父类的__init__方法        
>>> class C(B):
    def __init__(self):
        print('C.__init__')
        super().__init__()

#实例化C时,执行C的__init__方法,调用直接父类B的__init__方法,又进一步调用间接父类A的__init__方法
>>> c = C()
C.__init__
B.__init__
A.__init__

#重新定义子类C,继承关系不变,调用父类方法__init__时改用super(B,self)
>>> class C(B):
    def __init__(self):
        print('C.__init__')
        super(B,self).__init__()

#实例化C时,执行C的__init__方法,super(B,self)代理找到B的父类A,将self转换成B的实例,直接调用了A的__init__方法,跳过了调用B的__init__方法
>>> c = C()
C.__init__
A.__init__

#定义一个新类D
>>> class D(object):
    def __init__(self):
        print('D.__init__')

#重新定义C,继承关系不变,调用父类方法__init__时改用super(D,self)
>>> class C(B):
    def __init__(self):
        print('C.__init__')
        super(D,self).__init__()

#实例化C时,执行C的__init__方法,super(D,self)代理找到D的父类object,将self转换成D的实例,因为D和C无继承关系,self
无法转换成D的实例所以报错
>>> c= C()
C.__init__
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    c= C()
  File "<pyshell#13>", line 4, in __init__
    super(D,self).__init__()
TypeError: super(type, obj): obj must be an instance or subtype of type

23.6. 如果第2个参数时一个类型,则类型必须是第1个参数指定类型的子类,此种关系多用于多层继承关系的子类中,适用于类方法。

#定义父类A,并定义有一个类方法sayHello
>>> class A(object):
    @classmethod
    def sayHello(cls):
        print('A.sayHello')

# 定义子类B,继承A,重写类方法sayHello,在其中调用父类的sayHello方法
>>> class B(A):
    @classmethod
    def sayHello(cls):
        print('B.sayHello')
        super().sayHello()

# 定义子类C,继承B,重写类方法sayHello,在其中调用父类的sayHello方法
>>> class C(B):
    @classmethod
    def sayHello(cls):
        print('C.sayHello')
        super().sayHello()

#调用C的类方法sayHello,其调用C的直接父类B的类方法sayHello,调用时B的sayHello方法又调用B的直接父类A的类方法sayHello
>>> C.sayHello()
C.sayHello
B.sayHello
A.sayHello

#重新定义类C,继承关系不变,使用super(C,C)的方式调用父类方法
>>> class C(B):
    @classmethod
    def sayHello(cls):
        print('C.sayHello')
        super(C,C).sayHello()

#调用C的类方法sayHello,super(C,C)代理对象,找到C的直接父类B,然后调用C的直接父类B的类方法sayHello,调用时B的sayHello方法又调用B的直接父类A的类方法sayHello
>>> C.sayHello()
C.sayHello
B.sayHello
A.sayHello

#重新定义类C,继承关系不变,使用super(B,C)的方式调用父类方法
>>> class C(B):
    @classmethod
    def sayHello(cls):
        print('C.sayHello')
        super(B,C).sayHello()

#调用C的类方法sayHello,super(B,C)代理对象,找到B的直接父类A,然后调用B的直接父类A的类方法sayHello,中间不会调用B的sayHello方法
>>> C.sayHello()
C.sayHello
A.sayHello

#定义一个新类D,和A、B、C无继承关系
>>> class D(object):
    @classmethod
    def sayHello(cls):
        print('D.sayHello')

#重新定义类C,继承关系不变,使用super(D,C)的方式调用父类方法
>>> class C(B):
    @classmethod
    def sayHello(cls):
        print('C.sayHello')
        super(D,C).sayHello()

#调用C的类方法sayHello,super(D,C)代理对象,找到B的直接父类object,然后将C转换成D类,转换失败调用出错
>>> C.sayHello()
C.sayHello
Traceback (most recent call last):
  File "<pyshell#81>", line 1, in <module>
    C.sayHello()
  File "<pyshell#80>", line 5, in sayHello
    super(D,C).sayHello()
TypeError: super(type, obj): obj must be an instance or subtype of type

24、class object

24.1. object类是Python中所有类的基类,如果定义一个类时没有指定继承哪个类,则默认继承object类

>>> class A:
    pass

>>> issubclass(A,object)
True

24.2. object类定义了所有类的一些公共方法。

>>> dir(object)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

24.3. object类没有定义 __dict__,所以不能对object类实例对象尝试设置属性值。

>>> a = object()
>>> a.name = 'kim' # 不能设置属性
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    a.name = 'kim'
AttributeError: 'object' object has no attribute 'name'

#定义一个类A
>>> class A:
    pass

>>> a = A()
>>> 
>>> a.name = 'kim' # 能设置属性

第三类:序列操作,共8个

  

1、all(iterable)

如果可迭代对象的所有元素为真,或可迭代对象为空,则返回True,否则返回False 

 1 >>> L1 = [1,2,3,4,5]
 2 >>> L2 = []
 3 >>> L3 = [0,1,2,3]
 4 >>> all(L1)
 5 True
 6 >>> all(L2)
 7 True
 8 >>> all(L3)
 9 False
10 >>> all(L4)
View Code

2、any(iterable)

如果可迭代对象其中一个元素为真,就返回True,若可迭代对象为空或所有元素均为假,否则返回False 

1 >>> L1,L2,L3
2 ([0, None], [], [0, 1, 2, 3])
3 >>> any(L1)
4 False
5 >>> any(L2)
6 False
7 >>> any(L3)
8 True
View Code

3、filter(function, iterable)

3.1. filter函数用于过滤序列。过滤的方式则是采用传入的函数,循环调用序列的元素,如果函数计算的结果为True则保留元素,否则将舍弃该元素。

>>> a = list(range(1,10))   #定义序列
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def if_odd(x):       #定义奇数判断函数
    return x%2==1

>>> list(filter(if_odd,a))   #筛选序列中的奇数
[1, 3, 5, 7, 9]

3.2. 当function参数传入None时,序列中的元素值如果为False,也会自动舍弃。

>>> c = ['',False,'I',{}] #定义序列
>>> c
['', False, 'I', {}]

>>> list(filter(None,c)) #筛选函数为None,自动舍弃序列中的False值,空字符串、False值、空序列都是False值,所以丢弃
['I']

4、map(functioniterable...)

4.1. 函数接受一个函数类型参数、一个或者多个可迭代对象参数,返回一个可迭代器,此迭代器中每个元素,均是函数参数实例调用可迭代对象后的结果。

>>> a = map(ord,'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97, 98, 99, 100]

4.2. 当传入多个可迭代对象时,函数的参数必须提供足够多的参数,保证每个可迭代对象同一索引的值均能正确传入函数。

>>> a = map(ord,'abcd')
>>> list(a)
[97, 98, 99, 100]
>>> a = map(ord,'abcd','efg') # 传入两个可迭代对象,所以传入的函数必须能接收2个参数,ord不能接收2个参数,所以报错
>>> list(a)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    list(a)
TypeError: ord() takes exactly one argument (2 given)

>>> def f(a,b):
    return a + b

>>> a = map(f,'abcd','efg') # f函数可以接受2个参数
>>> list(a)
['ae', 'bf', 'cg']

4.3. 当传入多个可迭代对象时,且它们元素长度不一致时,生成的迭代器只到最短长度

>>> def f(a,b):
    return a + b

>>> a = map(f,'abcd','efg') # 选取最短长度为3
>>> list(a)
['ae', 'bf', 'cg']

5、next(iterator[, default])

5.1. 函数必须接收一个可迭代对象参数,每次调用的时候,返回可迭代对象的下一个元素。如果所有元素均已经返回过,则抛出StopIteration 异常

>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    next(a)
StopIteration

5.2. 函数可以接收一个可选的default参数,传入default参数后,如果可迭代对象还有元素没有返回,则依次返回其元素值,如果所有元素已经返回,则返回default指定的默认值而不抛出StopIteration 异常。

>>> a = iter('abcd')
>>> next(a,'e')
'a'
>>> next(a,'e')
'b'
>>> next(a,'e')
'c'
>>> next(a,'e')
'd'
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'

6、reversed(seq)

6.1. 函数功能是反转一个序列对象,将其元素从后向前颠倒构建成一个新的迭代器。

>>> a = reversed(range(10)) # 传入range对象
>>> a # 类型变成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

>>> a = ['a','b','c','d']
>>> a
['a', 'b', 'c', 'd']
>>> reversed(a) # 传入列表对象
<list_reverseiterator object at 0x031874D0>
>>> b = reversed(a)
>>> b # 类型变成迭代器
<list_reverseiterator object at 0x037C4EB0>
>>> list(b)
['d', 'c', 'b', 'a']

6.2. 如果参数不是一个序列对象,则其必须定义一个__reversed__方法。

# 类型Student没有定义__reversed__方法
>>> class Student:
    def __init__(self,name,*args):
        self.name = name
        self.scores = []
        for value in args:
            self.scores.append(value)

            
>>> a = Student('Bob',78,85,93,96)
>>> reversed(a) # 实例不能反转
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    reversed(a)
TypeError: argument to reversed() must be a sequence
>>> type(a.scores) # 列表类型
<class 'list'>


# 重新定义类型,并为其定义__reversed__方法
>>> class Student:
    def __init__(self,name,*args):
        self.name = name
        self.scores = []
        for value in args:
            self.scores.append(value)
    def __reversed__(self):
        self.scores = reversed(self.scores)

        
>>> a = Student('Bob',78,85,93,96)
>>> a.scores # 列表类型
[78, 85, 93, 96]
>>> type(a.scores)
<class 'list'>

>>> reversed(a)  # 实例变得可以反转
>>> a.scores # 反转后类型变成迭代器
<list_reverseiterator object at 0x0342F3B0>
>>> type(a.scores)
<class 'list_reverseiterator'>

>>> list(a.scores)
[96, 93, 85, 78]

7、sorted(iterable[, key][, reverse])

7.1. 函数功能对一个可迭代对象进行排序,返回一个排序后列表。

>>> a = sorted('dcabegf')
>>> a                    # 返回结果是列表
['a', 'b', 'c', 'd', 'e', 'f', 'g']

7.2. 函数调用时可以提供一个可选的命名参数key,它是一个方法,默认值是None,用来指定具体排序的算法;函数对可迭代对象每个元素使用key算法后再排序,返回的仍然是可迭代对象中的元素

>>> a = ['a','b','d','c','B','A']
>>> a
['a', 'b', 'd', 'c', 'B', 'A']

>>> sorted(a) # 默认按字符ascii码排序
['A', 'B', 'a', 'b', 'c', 'd']

>>> sorted(a,key = str.lower) # 转换成小写后再排序,'a''A'值一样,'b''B'值一样
['a', 'A', 'b', 'B', 'c', 'd']

7.3. 函数调用时可以提供一个可选的命名参数reverse,它的默认值是False,用来排序结果是否倒转。

>>> a = sorted('dcabegf')
>>> a
['a', 'b', 'c', 'd', 'e', 'f', 'g']

>>> a = sorted('dcabegf',reverse = True)           # 排序结果倒置
>>> a
['g', 'f', 'e', 'd', 'c', 'b', 'a']

8、zip(*iterables)

8.1. 函数功能是聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器。

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> xy = zip(x,y)
>>> xy                 #xy的类型是zip类型
<zip object at 0x0429C828>
#导入Iterable
>>> from collections import Iterable
>>> isinstance(xy,Iterable)     #判断是否可迭代对象
True
>>> list(xy)               #结果
[(1, 4), (2, 5), (3, 6)]

8.2. 如果传入的迭代器长度不一致,最短长度的迭代器迭代结束后停止聚合。

>>> x = [1,2,3]       #长度3
>>> y = [4,5,6,7,8]     #长度5
>>> list(zip(x,y))     # 取最小长度3
[(1, 4), (2, 5), (3, 6)]

8.3. 如果只传入一个迭代器,则返回的单个元素元组的迭代器。

>>> list(zip([1,2,3]))
[(1,), (2,), (3,)]

8.4. 如果不传入参数,则返回空的迭代器。

>>> list(zip())
[]

8.5. zip(*[iter(s)]*n)等效于调用zip(iter(s),iter(s),...,iter(s))。

>>> x = [1,2,3]

>>> list(zip(*[x]*3))
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

>>> list(zip(x,x,x))
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

第四类:对象操作,共9个

1 、 help([object])

说明:

  1. 在解释器交互界面,不传参数调用函数时,将激活内置的帮助系统,并进入帮助系统。在帮助系统内部输入模块、类、函数等名称时,将显示其使用说明,输入quit退出内置帮助系统,并返回交互界面。

 
>>> help() #不带参数

Welcome to Python 3.5's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

#进入内置帮助系统  >>> 变成了 help>
help> str #str的帮助信息
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 ................................


help> 1 #不存在的模块名、类名、函数名
No Python documentation found for '1'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

help> quit #退出内置帮助系统

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

# 已退出内置帮助系统,返回交互界面 help> 变成 >>>
>>> 
 

  2. 在解释器交互界面,传入参数调用函数时,将查找参数是否是模块名、类名、函数名,如果是将显示其使用说明。

 
>>> help(str) 
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
  ***************************

2、dir([object])

说明:

  1. 当不传参数时,返回当前作用域内的变量、方法和定义的类型列表。

>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> a = 10 #定义变量a
>>> dir() #多了一个a
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']

  2. 当参数对象是模块时,返回模块的属性、方法列表。

 
>>> import math
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
 

  3. 当参数对象是类时,返回类及其子类的属性、方法列表。

 
>>> class A:
    name = 'class'

    
>>> a = A()
>>> dir(a) #name是类A的属性,其他则是默认继承的object的属性、方法
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
 

  4. 当对象定义了__dir__方法,则返回__dir__方法的结果

 
>>> class B:
    def __dir__(self):
        return ['name','age']

>>> b = B()
>>> dir(b) #调用 __dir__方法
['age', 'name']

3、id(object)

说明:
  
  1. 返回对象的唯一标识符,用整数表示。在程序生命周期内,这个标识符常量是唯一的。
>>> a = 1
>>> id(a)
1652447504
>>> id(1.0)
66116592
>>> a = 'some text'
>>> id(a)
69228568

4、hash(object)

说明:  

  1. 返回对象的哈希值,用整数表示。哈希值在字典查找时,可用于快速比较键的值。

>>> hash('good good study')
1032709256

  2. 相等的数值,即使类型不一致,计算的哈希值是一样的。

>>> 1.0 == 1
True
>>> hash(1.0)
1
>>> hash(1)
1
>>> hash(1.0000)
1

5、

class type(object)

class type(namebasesdict)

说明:

  1. 函数只传入一个参数时,返回参数对象的类型。 返回值是一个类型对象,通常与对象.__ class__返回的对象相同。

 
#定义类型A
>>> class A:
    name = 'defined in A'

#创建类型A实例a
>>> a = A()

#a.__class__属性
>>> a.__class__
<class '__main__.A'>

#type(a)返回a的类型
>>> type(a)
<class '__main__.A'>

#测试类型
>>> type(a) == A
True
 

  2. 虽然可以通过type函数来检测一个对象是否是某个类型的实例,但是更推荐使用isinstance函数,因为isinstance函数考虑了父类子类间继承关系。

 
#定义类型B,继承A
>>> class B(A):
    age = 2

#创建类型B的实例b
>>> b = B()

#使用type函数测试b是否是类型A,返回False
>>> type(b) == A
False

#使用isinstance函数测试b是否类型A,返回True
>>> isinstance(b,A)
True
 

  3. 函数另一种使用方式是传入3个参数,函数将使用3个参数来创建一个新的类型。其中第一个参数name将用作新的类型的类名称,即类型的__name__属性;第二个参数是一个元组类型,其元素的类型均为类类型,将用作新创建类型的基类,即类型的__bases__属性;第三个参数dict是一个字典,包含了新创建类的主体定义,即其值将复制到类型的__dict__属性中。

 
#定义类型A,含有属性InfoA
>>> class A(object):
    InfoA = 'some thing defined in A'

#定义类型B,含有属性InfoB
>>> class B(object):
    InfoB = 'some thing defined in B'

#定义类型C,含有属性InfoC
>>> class C(A,B):
    InfoC = 'some thing defined in C'

#使用type函数创建类型D,含有属性InfoD
>>> D = type('D',(A,B),dict(InfoD='some thing defined in D'))

#C、D的类型
>>> C
<class '__main__.C'>
>>> D
<class '__main__.D'>

#分别创建类型C、类型D的实例
>>> c = C()
>>> d = D()

#分别输出实例c、实例b的属性
>>> (c.InfoA,c.InfoB,c.InfoC)
('some thing defined in A', 'some thing defined in B', 'some thing defined in C')
>>> (d.InfoA,d.InfoB,d.InfoD)
('some thing defined in A', 'some thing defined in B', 'some thing defined in D')

6、len(s)

1. 返回对象的长度,参数可以是序列(比如字符串、字节数组、元组、列表和range对象),或者是集合(比如字典、集合、不可变集合)
 
>>> len('abcd') # 字符串
4
>>> len(bytes('abcd','utf-8')) # 字节数组
4
>>> len((1,2,3,4)) # 元组
4
>>> len([1,2,3,4]) # 列表
4
>>> len(range(1,5)) # range对象
4
>>> len({'a':1,'b':2,'c':3,'d':4}) # 字典
4
>>> len({'a','b','c','d'}) # 集合
4
>>> len(frozenset('abcd')) #不可变集合
4
 

  2. 如果参数为其它类型,则其必须实现__len__方法,并返回整数,否则报错。

 
>>> class A:
    def __init__(self,name):
        self.name = name
    def __len__(self):
        return len(self.name)

>>> a = A('')
>>> len(a)
0
>>> a = A('Aim')
>>> len(a)
3
>>> class B:
    pass

>>> b = B()
>>> len(b)
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    len(b)
TypeError: object of type 'B' has no len()
>>> class C:
    def __len__(self):
        return 'len'

>>> c = C()
>>> len(c)
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    len(c)
TypeError: 'str' object cannot be interpreted as an integer

7、ascii(object)

说明:

    1. 返回一个可打印的对象字符串方式表示,如果是非ascii字符就会输出x,u或U等字符来表示。与python2版本里的repr()是等效的函数。

>>> ascii(1)
'1'
>>> ascii('&')
"'&'"
>>> ascii(9000000)
'9000000'
>>> ascii('中文') #非ascii字符
"'\u4e2d\u6587'"

8、format(value[, format_spec])

说明:

  1. 函数功能将一个数值进行格式化显示。

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

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

  3. 对于不同的类型,参数format_spec可提供的值都不一样

 
#字符串可以提供的参数 's' None
>>> format('some string','s')
'some string'
>>> format('some string')
'some string'

#整形数值可以提供的参数有 '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<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
>>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
'3e-05'
>>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
'3.1e-05'
>>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
'3.14e-05'
>>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
'3.14E-05'
>>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
'3'
>>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
'3.1'
>>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
'3.14'
>>> format(0.00003141566,'.1n') #和g相同
'3e-05'
>>> format(0.00003141566,'.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'

9、vars([object])

说明

  1. 当函数不接收参数时,其功能和locals函数一样,返回当前作用域内的局部变量。

 
#不带参数功能和locals函数一样
>>> v1 = vars()
>>> l1 = locals()
>>> v1
{'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'v1': {...}, 'l1': {...}, '__spec__': None, '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> l1
{'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'v1': {...}, 'l1': {...}, '__spec__': None, '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
 

  2. 当函数接收一个参数时,参数可以是模块、类、类实例,或者定义了__dict__属性的对象。

 
#作用于模块
>>> import time
>>> vars(time)
{'gmtime': <built-in function gmtime>, 'tzname': ('Öйú±ê׼ʱ¼ä', 'ÖйúÏÄÁîʱ'), 'timezone': -28800, 'struct_time': <class 'time.struct_time'>, 'ctime': <built-in function ctime>, 'perf_counter': <built-in function perf_counter>, 'mktime': <built-in function mktime>, 'localtime': <built-in function localtime>, 'time': <built-in function time>, '__package__': '', 'altzone': -32400, 'clock': <built-in function clock>, 'strptime': <built-in function strptime>, 'monotonic': <built-in function monotonic>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'get_clock_info': <built-in function get_clock_info>, 'sleep': <built-in function sleep>, 'process_time': <built-in function process_time>, '__name__': 'time', '_STRUCT_TM_ITEMS': 9, '__spec__': ModuleSpec(name='time', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'), '__doc__': 'This module provides various functions to manipulate time values.

There are two standard representations of time.  One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).

The other representation is a tuple of 9 integers giving local time.
The tuple items are:
  year (including century, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.

Variables:

timezone -- difference in seconds between UTC and local standard time
altzone -- difference in  seconds between UTC and local DST time
daylight -- whether local time should reflect DST
tzname -- tuple of (standard time zone name, DST time zone name)

Functions:

time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone', 'strftime': <built-in function strftime>, 'asctime': <built-in function asctime>, 'daylight': 0}

#作用于类
>>> vars(slice)
mappingproxy({'__ne__': <slot wrapper '__ne__' of 'slice' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'slice' objects>, '__reduce__': <method '__reduce__' of 'slice' objects>, 'start': <member 'start' of 'slice' objects>, 'indices': <method 'indices' of 'slice' objects>, '__ge__': <slot wrapper '__ge__' of 'slice' objects>, 'stop': <member 'stop' of 'slice' objects>, '__eq__': <slot wrapper '__eq__' of 'slice' objects>, 'step': <member 'step' of 'slice' objects>, '__hash__': None, '__doc__': 'slice(stop)
slice(start, stop[, step])

Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).', '__repr__': <slot wrapper '__repr__' of 'slice' objects>, '__le__': <slot wrapper '__le__' of 'slice' objects>, '__gt__': <slot wrapper '__gt__' of 'slice' objects>, '__new__': <built-in method __new__ of type object at 0x6A91B420>, '__lt__': <slot wrapper '__lt__' of 'slice' objects>})

#作用于类实例
>>> class A(object):
    pass

>>> a.__dict__
{}
>>> vars(a)
{}
>>> a.name = 'Kim'
>>> a.__dict__
{'name': 'Kim'}
>>> vars(a)
{'name': 'Kim'}

第五类、反射操作,共8个

1、__import__(nameglobals=Nonelocals=Nonefromlist=()level=0)

说明:

  1. 函数功能用于动态的导入模块,主要用于反射或者延迟加载模块。

  2. __import__(module)相当于import module

  先定义两个模块mian.py和index.py,两个文件在同一目录下:

 
#index.py

print ('index')

def sayHello():
    print('hello index')

def sayHelloZhCn():
    print('你好 index')
 
 
#mian.py
print ('main')

index = __import__('index')
dir(index)
index.sayHello()
index.sayHelloZhCn()
 

  执行main.py,可以证实动态加载了index.py,__import__返回的模块也是index模块

C:UsersAdminDocumentsPython3importtest>python main.py
main
index
hello index
你好 index

  3. __import__(package.module)相当于from package import name,如果fromlist不传入值,则返回package对应的模块,如果fromlist传入值,则返回package.module对应的模块。

  先定义archives包,其中包含user和role两个模块:

#__index__.py
print ('archives.__index__')

def sayHello():
    print('hello archives')
#user.py
print ('user')

def sayHello():
    print('hello user')
#role.py
print ('role')

def sayHello():
    print('hello role')

  结构如下:

  修改mian.py:

 
#main.py
print ('main')

archives = __import__('archives')
archives.sayHello()
archives.user
 

  执行main.py,可以证实动态加载了archives包,__import__返回的模块也是archives模块

 
C:UsersAdminDocumentsPython3importtest>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:

#main.py
print ('main')

archives = __import__('archives.user')
archives.sayHello()
print(archives.user)

  执行main.py,可以证实动态加载了archives包的user模块,__import__返回的模块也是archives模块

 
C:UsersAdminDocumentsPython3importtest>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:

 
#main.py
print ('main')

archives = __import__('archives.user',fromlist = ('user',))
archives.sayHello()
print(archives)
 

  执行main.py,可以证实动态加载了archives包的user模块,__import__返回的模块是user模块

 
C:UsersAdminDocumentsPython3importtest>python main.py
main
archives.__index__
user
hello user
<module 'archives.user' from 'C:\Users\Admin\Documents\Python3\import
test\archives\user.py'>

2、isinstance(objectclassinfo)

说明:

  1. 函数功能用于判断对象是否是类型对象的实例,object参数表示需要检查的对象,calssinfo参数表示类型对象。

  2. 如果object参数是classinfo类型对象(或者classinfo类对象的直接、间接、虚拟子类)的实例,返回True。

 
>>> isinstance(1,int)
True
>>> isinstance(1,str)
False

# 定义3各类:C继承B,B继承A
>>> class A:
    pass

>>> class B(A):
    pass

>>> class C(B):
    pass

>>> a = A()
>>> b = B()
>>> c = C()
>>> isinstance(a,A) #直接实例
True
>>> isinstance(a,B)
False
>>> isinstance(b,A) #子类实例 
True
>>> isinstance(c,A) #孙子类实例
True
 

  3. 如果object参数传入的是类型对象,则始终返回False。

>>> isinstance(str,str)
False
>>> isinstance(bool,int)
False

  4. 如果classinfo类型对象,是多个类型对象组成的元组,如果object对象是元组的任一类型对象中实例,则返回True,否则返回False。

>>> isinstance(a,(B,C))
False
>>> isinstance(a,(A,B,C))
True

  5. 如果classinfo类型对象,不是一个类型对象或者由多个类型对象组成的元组,则会报错(TypeError)。

>>> isinstance(a,[A,B,C])
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    isinstance(a,[A,B,C])
TypeError: isinstance() arg 2 must be a type or tuple of types

3、issubclass(classclassinfo)

说明:
  
  1. 函数功能用于判断一个类型对象是否是另一个类型对象的子类,class参数表示需要检查的类型对象,calssinfo参数表示需要对比类型对象。
  2. 如果class参数是classinfo类型对象(或者classinfo类对象的直接、间接、虚拟子类)的实例,返回True。
 
>>> issubclass(bool,int)
True
>>> issubclass(bool,(str))
False

>>> class A:
    pass
>>> class B(A):
    pass
>>> issubclass(B,A)
True
 

  3. 任何一个类都是自己类的子类,即class和calssinfo传入相同类型时,返回True。

>>> class A:
    pass

>>> issubclass(A,A)
True

  4. 如果classinfo类型对象,是多个类型对象组成的元组,如果class类型对象是元组的任一类型对象的子类,则返回True,否则返回False。

 
>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False

>>> issubclass(bool,(str,int))
True
 

  5. 如果classinfo类型对象,不是一个类型对象或者由多个类型对象组成的元组,则会报错(TypeError)。

>>> issubclass(bool,[str,int])
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    issubclass(bool,[str,int])
TypeError: issubclass() arg 2 must be a class or tuple of classes

4、hasattr(objectname)

说明:
  
  1. 函数功能用来检测对象object中是否含有名为name的属性,如果有则返回True,如果没有返回False
 
#定义类A
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> s = Student('Aim')
>>> hasattr(s,'name') #a含有name属性
True
>>> hasattr(s,'age') #a不含有age属性
False

5、getattr(objectname[, default])

说明:
  
  1. 函数功能是从对象object中获取名称为name的属性,等效与调用object.name。
 
#定义类Student
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> s = Stduent('Aim')
>>> getattr(s,'name') #等效于调用s.name
'Aim'
>>> s.name
'Aim'
 

  2. 函数第三个参数default为可选参数,如果object中含义name属性,则返回name属性的值,如果没有name属性,则返回default值,如果default未传入值,则报错。

 
#定义类Student
>>> class Student:
    def __init__(self,name):
        self.name = name

>>> getattr(s,'name') #存在属性name
'Aim'

>>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值
6

>>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'

6、setattr(objectnamevalue)

说明:

  1. setattr函数和getattr函数是对应的。一个设置对象的属性值,一个获取对象属性值。

  2. 函数有3个参数,功能是对参数object对象,设置名为name的属性的属性值为value值。

 
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name','Bob')
>>> a.name
'Bob'
 

  3. name属性可以是object对象的一个已经存在的属性,存在的话就会更新其属性值;如果name属性不存在,则对象将创建name名称的属性值,并存储value值。等效于调用object.name = value。

 
>>> a.age # 不存在age属性
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    a.age
AttributeError: 'Student' object has no attribute 'age'

>>> setattr(a,'age',10) # 执行后 创建 age属性
>>> a.age  # 存在age属性了
10
>>> a.age = 12 # 等效于调用object.name
>>> a.age
12

7、delattr(objectname)

说明:
  
  1. 函数作用用来删除指定对象的指定名称的属性,和setattr函数作用相反。
 
#定义类A
>>> class A:
    def __init__(self,name):
        self.name = name
    def sayHello(self):
        print('hello',self.name)

#测试属性和方法
>>> a.name
'小麦'
>>> a.sayHello()
hello 小麦

#删除属性
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'
 

   2. 当属性不存在的时候,会报错。

 
>>> a.name #属性name已经删掉,不存在
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'

>>> delattr(a,'name') #再删除会报错
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    delattr(a,'name')
AttributeError: name
 

   3. 不能删除对象的方法。

 
>>> a.sayHello
<bound method A.sayHello of <__main__.A object at 0x03F014B0>>
>>> delattr(a,'sayHello') #不能用于删除方法
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    delattr(a,'sayHello')
AttributeError: sayHello
>>>

8、callable(object)

说明:

  1. 方法用来检测对象是否可被调用,可被调用指的是对象能否使用()括号的方法调用。

 

>>> callable(callable)
True
>>> callable(1)
False
>>> 1()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
1()
TypeError: 'int' object is not callable
>>>

 

  2. 可调用对象,在实际调用也可能调用失败;但是不可调用对象,调用肯定不成功。

  3. 类对象都是可被调用对象,类的实例对象是否可调用对象,取决于类是否定义了__call__方法。

 
>>> class A: #定义类A
    pass

>>> callable(A) #类A是可调用对象
True
>>> a = A() #调用类A
>>> callable(a) #实例a不可调用
False
>>> a() #调用实例a失败
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    a()
TypeError: 'A' object is not callable


>>> class B: #定义类B
    def __call__(self):
        print('instances are callable now.')

        
>>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.

第六类、变量操作、共2个

1、globals()

说明:
  1. 返回当前作用域内全局变量的字典。
>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一个a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

2、locals()

说明:

  1. 函数功能返回当前作用域内的局部变量和其值组成的字典,与globals函数类似(返回全局变量)

 
>>> locals()
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}

>>> a = 1

>>> locals() # 多了一个key为a值为1的项
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'a': 1, '__doc__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}
 

  2. 可用于函数内。

 
>>> def f():
    print('before define a ')
    print(locals()) #作用域内无变量
    a = 1
    print('after define a')
    print(locals()) #作用域内有一个a变量,值为1

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{'a': 1}
 

  3. 返回的字典集合不能修改。

 
>>> def f():
    print('before define a ')
    print(locals()) # 作用域内无变量
    a = 1
    print('after define a')
    print(locals()) # 作用域内有一个a变量,值为1
    b = locals()
    print('b["a"]: ',b['a']) 
    b['a'] = 2 # 修改b['a']值
    print('change locals value')
    print('b["a"]: ',b['a'])
    print('a is ',a) # a的值未变

    
>>> f()
before define a 
{}
after define a
{'a': 1}
b["a"]:  1
change locals value
b["a"]:  2
a is  1
>>>

第七类:交互操作、共2个

1、print(*objectssep=' 'end=' 'file=sys.stdoutflush=False)

说明:

  1. 用于对象打印输出。通过命名参数sep来确定多个输出对象的分隔符(默认' '),通过命名参数end确定输出结果的结尾(默认' '),通过命名参数file确定往哪里输出(默认sys.stdout),通过命名参数fiush确定输出是否使用缓存(默认False)。

 
>>> print(1,2,3)
1 2 3
>>> print(1,2,3,sep = '+')
1+2+3
>>> print(1,2,3,sep = '+',end = '=?')
1+2+3=?
 

  2. sep、end、file、flush都必须以命名参数方式传参,否则将被当做需要输出的对象了。

>>> print(1,2,3,'+','=?')
1 2 3 + =?

  3. sep和end参数必须是字符串;或者为None,为None时意味着将使用其默认值。

 
>>> print(1,2,3,sep = 97,end = 100)
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    print(1,2,3,sep = 97,end = 100)
TypeError: sep must be None or a string, not int
>>> print(1,2,3,sep = None,end = None)
1 2 3
 

  4. 不给print传递任何参数,将只输出end参数的默认值。

>>> print()

>>> print(end = 'by 2016')
by 2016

  5. file参数必须是一个含有write(string) 方法的对象。

复制代码
>>> class A:
    @staticmethod    
    def write(s):
        print(s)

        
>>> a = A()
>>> print(1,2,3,sep = '+',end = '=?',file = a)
1
+
2
+
3
=?

2、input([prompt])

说明:

  1. 如果提供了promat参数,首先将参数值输出到标准的输出,并且不换行。函数读取用户输入的值,将其转换成字符串。

>>> s = input('please input your name:')
please input your name:Ain
>>> s
'Ain'

第八类、文件操作,共1个

1、open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

说明:

  1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作。

  2. file参数表示的需要打开文件的相对路径(当前工作目录)或者一个绝对路径,当传入路径不存在此文件会报错。或者传入文件的句柄。

 
>>> a = open('test.txt') # 相对路径
>>> a
<_io.TextIOWrapper name='test.txt' mode='r' encoding='cp936'>
>>> a.close()

>>> a = open(r'D:PythonPython35-32	est.txt') # 绝对路径
>>> a
<_io.TextIOWrapper name='D:\Python\Python35-32\test.txt' mode='r' encoding='cp936'>
 

  3. mode参数表示打开文件的模式,常见的打开模式有如下几种,实际调用的时候可以根据情况进行组合。

    'r': 以只读模式打开(缺省模式)(必须保证文件存在)
    'w':以只写模式打开。若文件存在,则会自动清空文件,然后重新创建;若文件不存在,则新建文件。使用这个模式必须要保证文件所在目录存在,文件可以不存在。该模式下不能使用read*()方法

    'a':以追加模式打开。若文件存在,则会追加到文件的末尾;若文件不存在,则新建文件。该模式不能使用read*()方法。

  

  下面四个模式要和上面的模式组合使用
    'b':以二进制模式打开

    't': 以文本模式打开(缺省模式)
    '+':以读写模式打开
    'U':以通用换行符模式打开

  常见的mode组合


    'r'或'rt':     默认模式,文本读模式
    'w'或'wt':   以文本写模式打开(打开前文件会被清空)
    'rb':          以二进制读模式打开
    'ab':         以二进制追加模式打开
    'wb':        以二进制写模式打开(打开前文件会被清空)
    'r+':         以文本读写模式打开,可以写到文件任何位置;默认写的指针开始指在文件开头, 因此会覆写文件
    'w+':        以文本读写模式打开(打开前文件会被清空)。可以使用read*()
    'a+':         以文本读写模式打开(写只能写在文件末尾)。可以使用read*()
    'rb+':       以二进制读写模式打开
    'wb+':      以二进制读写模式打开(打开前文件会被清空)
    'ab+':      以二进制读写模式打开

 
# t为文本读写,b为二进制读写
>>> a = open('test.txt','rt')
>>> a.read()
'some text'
>>> a = open('test.txt','rb')
>>> a.read()
b'some text'

# r为只读,不能写入;w为只写,不能读取
>>> a = open('test.txt','rt')
>>> a.write('more text')
Traceback (most recent call last):
  File "<pyshell#67>", line 1, in <module>
    a.write('more text')
io.UnsupportedOperation: write
>>> a = open('test.txt','wt')
>>> a.read()
Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    a.read()
io.UnsupportedOperation: not readable

#其它不一一举例了
 

  4. buffering表示文件在读取操作时使用的缓冲策略。

      0:    代表buffer关闭(只适用于二进制模式)
      1:    代表line buffer(只适用于文本模式)
      >1:  表示初始化的buffer大小

  5. encoding参数表示读写文件时所使用的的文件编码格式。

  假设现在test.txt文件以utf-8编码存储了一下文本:

     

 
>>> a = open('test.txt','rt') # 未正确指定编码,有可能报错
>>> a.read()
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    a.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 8: illegal multibyte sequence

>>> a = open('test.txt','rt',encoding = 'utf-8')
>>> a.read()
'我是第1行文本,我将被显示在屏幕
我是第2行文本,我将被显示在屏幕
我是第3行文本,我将被显示在屏幕'
>>> 
 

  6. errors参数表示读写文件时碰到错误的报错级别。

  常见的报错基本有:

  • 'strict' 严格级别,字符编码有报错即抛出异常,也是默认的级别,errors参数值传入None按此级别处理.
  • 'ignore' 忽略级别,字符编码有错,忽略掉.
  • 'replace' 替换级别,字符编码有错的,替换成?. 
 
>>> a = open('test.txt','rt',encoding = 'utf-8')
>>> a.read()
'我是第1行文本,我将被显示在屏幕
我是第2行文本,我将被显示在屏幕
我是第3行文本,我将被显示在屏幕'
>>> a = open('test.txt','rt')
>>> a.read()
Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    a.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 8: illegal multibyte sequence
>>> a = open('test.txt','rt',errors = 'ignore' )
>>> a.read()
'鎴戞槸绗1琛屾枃鏈锛屾垜灏嗚鏄剧ず鍦ㄥ睆骞
鎴戞槸绗2琛屾枃鏈锛屾垜灏嗚鏄剧ず鍦ㄥ睆骞
鎴戞槸绗3琛屾枃鏈锛屾垜灏嗚鏄剧ず鍦ㄥ睆骞'
>>> a = open('test.txt','rt',errors = 'replace' )
>>> a.read()
'鎴戞槸绗�1琛屾枃鏈�锛屾垜灏嗚��鏄剧ず鍦ㄥ睆骞�
鎴戞槸绗�2琛屾枃鏈�锛屾垜灏嗚��鏄剧ず鍦ㄥ睆骞�
鎴戞槸绗�3琛屾枃鏈�锛屾垜灏嗚��鏄剧ず鍦ㄥ睆骞�'
 

  7. newline表示用于区分换行符(只对文本模式有效,可以取的值有None,' ',' ','',' ')

 
>>> a = open('test.txt','rt',encoding = 'utf-8',newline = '
')
>>> a.readline()
'我是第1行文本,我将被显示在屏幕
'
>>> a = open('test.txt','rt',encoding = 'utf-8',newline = '
')
>>> a.readline()
'我是第1行文本,我将被显示在屏幕
'
 

  8. closefd表示传入的file参数类型(缺省为True),传入文件路径时一定为True,传入文件句柄则为False。

 
>>> a = open('test.txt','rt',encoding = 'utf-8',newline = '
',closefd = False)
Traceback (most recent call last):
  File "<pyshell#115>", line 1, in <module>
    a = open('test.txt','rt',encoding = 'utf-8',newline = '
',closefd = False)
ValueError: Cannot use closefd=False with file name
>>> a = open('test.txt','rt',encoding = 'utf-8',newline = '
',closefd = True)

第九类、编译执行、共4个

1、compile(sourcefilenamemodeflags=0dont_inherit=Falseoptimize=-1)

说明:
  1. 将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。
  2. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。
  3. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。
  4. 参数mode:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,mode应指定为‘exec’;当source中只包含一个简单的求值表达式,mode应指定为‘eval’;当source中包含了交互式命令语句,mode应指定为'single'。
 
>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10


>>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    name
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'pythoner'
>>> name #执行后name变量有值
"'pythoner'"

2、eval(expressionglobals=Nonelocals=None)

说明:
  
  1. 执行动态语句,返回语句执行的值。
>>> eval('1+2+3+4')
10

  2. 第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。

  3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量。

 
>>> g = {'num':2}

>>> eval('num + 2') #num未定义
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    eval('num + 2')
  File "<string>", line 1, in <module>
NameError: name 'num' is not defined

>>> eval('num + 2',g) #g中有定义num,可执行
4
 

   4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量

>>> g = {'num1':2}
>>> l = {'num2':4}
>>> eval('num1+num2',g,l)
6

   5. 为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,Python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。

 
>>> g = {}
>>> eval('abs(-1)',g)
1

>>> g = {'__builtins__':{}}
>>> eval('abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    eval('abs(-1)',g)
  File "<string>", line 1, in <module>
NameError: name 'abs' is not defined
 

   6. 当globals参数不提供是,Python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。

 
>>> num = 1
>>> eval('num+2')
3

>>> globals() #返回字典中含有num的key
{'__doc__': None, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}

>>> eval('num+2',{}) #locals参数未提供,locals参数=globals参数
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    eval('num+2',{})
  File "<string>", line 1, in <module>
NameError: name 'num' is not defined

>>> l = locals() 
>>> eval('num+2',{},l) #locals参数含有num的key,能求值
3

>>> locals()
{'__doc__': None, 'l': {...}, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>> 

3、exec(object[, globals[, locals]])

说明:
  
  1.  exec函数和eval函数类似,也是执行动态语句,只不过eval函数只用于执行表达式求值,而exec函数主要用于执行语句块。
 
>>> eval('a=1+2') #执行语句报错
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    eval('a=1+2')
  File "<string>", line 1
    a=1+2
     ^
SyntaxError: invalid syntax

>>> exec('a=1+2') #执行语句
>>> a
3
 

  2. 第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。

  3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量

 
>>> g = {'num':2}
>>> type(g)
<class 'dict'>

>>> exec('num2 = num + 2',g)

>>> g['num']
2
>>> g['num2'] #收集了exec中定义的num2全局变量
4
 

  4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量

 
>>> g = {'num':2}
>>> type(g)
<class 'dict'>
>>> l = {'num2':3}
>>> type(l)
<class 'dict'>

>>> exec('''
num2 = 13
num3 = num + num2
''',g,l)

>>> l['num2'] #l中num2值已经改变
13
 

  5. 为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,Python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。

 
>>> g = {}
>>> exec('a = abs(-1)',g)
>>> 

>>> g = {'__builtins__':{}}
>>> exec('a = abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    exec('a = abs(-1)',g)
  File "<string>", line 1, in <module>
NameError: name 'abs' is not defined
 

  6. 当globals参数不提供是,Python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。

 
>>> num = 1
>>> exec('num2 = num + 1')
>>> globals()
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'num2': 2, 'num': 1}
>>> 
>>> 
>>> exec('num2 = num + 1',{}) #指定了globals参数,globals中无num变量 执行失败
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    exec('num2 = num + 1',{})
  File "<string>", line 1, in <module>
NameError: name 'num' is not defined


>>> l = locals()
>>> l
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}
>>> 
>>> exec('num3 = num + 1',{},l)#指定了globals参数,globals中无num变量,指定了locals变量,locals变量含有num变量 执行成功
>>> l
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, 'num3': 2, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}
>>> 

4、repr(object)

说明:
  1. 函数功能返回一个对象的字符串表现形式。其功能和str函数比较类似,但是两者也有差异:函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式。
>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"

  2. repr函数的结果一般能通过eval()求值的方法获取到原对象。

>>> eval(repr(a))
'some text'

  3. 对于一般的类型,对其实例调用repr函数返回的是其所属的类型和被定义的模块,以及内存地址组成的字符串。

 
>>> class Student:
    def __init__(self,name):
        self.name = name

>>> a = Student('Bob')
>>> repr(a)
'<__main__.Student object at 0x037C4EB0>'
 

  4. 如果要改变类型的repr函数显示信息,需要在类型中定义__repr__函数进行控制。

 
>>> class Student:
    def __init__(self,name):
        self.name = name
    def __repr__(self):
        return ('a student named ' + self.name)

>>> b = Student('Kim')
>>> repr(b)
'a student named Kim'

第十类、装饰器、共3个

1、 class property(fget=Nonefset=Nonefdel=Nonedoc=None)

说明:

  1. property是一个类,其作用是用来包装类的属性,这个属性可以根据实际需要,控制是否可读(设置fget参数)、可写(设置fset参数)、可删除(设置fdel参数)。

 
class C:
    def __init__(self):
        self._x = '_x in C'

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")
 
 
>>> c = C()
>>> c.x # 调用 getx
'_x in C'

>>> c.x = 'x had changed' # 调用 setx
>>> c.x # 调用 getx
'x had changed'

>>> del c.x  # 调用 delx
>>> c.x # 调用 getx
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    c.x
  File "<pyshell#28>", line 6, in getx
    return self._x
AttributeError: 'C' object has no attribute '_x'
 

  2. 参数doc表示的是属性的说明,如果没有指定,将从fget参数指定的方法中读取。

 
>>> help(c)
Help on C in module __main__ object:

class C(builtins.object)
 |  Methods defined here:
 |  
 |  __init__(self)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  delx(self)
 |  
 |  getx(self)
 |  
 |  setx(self, value)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  x
 |      I'm the 'x' property.

# 最后一行中 文档字符串 为I'm the 'x' property.

>>> class C:
    def __init__(self):
        self._x = '_x in C'

    def getx(self):
        """I'm the 'x' property. provide by getx"""
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx)

    
>>> help(C)
Help on class C in module __main__:

class C(builtins.object)
 |  Methods defined here:
 |  
 |  __init__(self)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  delx(self)
 |  
 |  getx(self)
 |      I'm the 'x' property. provide by getx
 |  
 |  setx(self, value)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  x
 |      I'm the 'x' property. provide by getx

# 最后一行中 文档字符串 为 I'm the 'x' property. provide by getx
 

  3. property更优雅的做法是用作装饰器,装饰过的方法就可以以属性方式调用。同时将生成.setter和.deleter装饰器,用于指定可入方法,删除方法。

 
>>> class C:
    def __init__(self):
        self._x = '_x in C'

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
 
 
>>> c = C()
>>> c.x # 调用 getx
'_x in C'

>>> c.x = 'x had changed' # 调用 setx
>>> c.x # 调用 getx
'x had changed'

>>> del c.x  # 调用 delx
>>> c.x # 调用 getx
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    c.x
  File "<pyshell#28>", line 6, in getx
    return self._x
AttributeError: 'C' object has no attribute '_x'
 

  4. 不直接使用字段,而使用属性,主要因为可以控制外部对类字段的恶意修改和删除,而且可以再设置属性值的时候进行适当的验证。

 
>>> class C:
    def __init__(self):
        self._name = ''
    @property
    def name(self):
        """i'm the 'name' property."""
        return self._name
    @name.setter
    def name(self,value):
        if value is None:
            raise RuntimeError('name can not be None')
        else:
            self._name = value

            
>>> c = C()

>>> c.name # 访问属性
''
>>> c.name = None # 设置属性时进行验证
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    c.name = None
  File "<pyshell#81>", line 11, in name
    raise RuntimeError('name can not be None')
RuntimeError: name can not be None

>>> c.name = 'Kim' # 设置属性
>>> c.name # 访问属性
'Kim'

>>> del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    del c.name
AttributeError: can't delete attribute
>>> c.name
'Kim'

2、classmethod(function)

说明:

  1. classmethod 是一个装饰器函数,用来标示一个方法为类方法

  2. 类方法的第一个参数是类对象参数,在方法被调用的时候自动将类对象传入,参数名称约定为cls

  3. 如果一个方法被标示为类方法,则该方法可被类对象调用(如 C.f()),也可以被类的实例对象调用(如 C().f())

 
>>> class C:
    @classmethod
    def f(cls,arg1):
        print(cls)
        print(arg1)

        
>>> C.f('类对象调用类方法')
<class '__main__.C'>
类对象调用类方法

>>> c = C()
>>> c.f('类实例对象调用类方法')
<class '__main__.C'>
类实例对象调用类方法
 

  4. 类被继承后,子类也可以调用父类的类方法,但是第一个参数传入的是子类的类对象

>>> class D(C):
    pass

>>> D.f("子类的类对象调用父类的类方法")
<class '__main__.D'>
子类的类对象调用父类的类方法

3、staticmethod(function)

说明:

  1. 类中普通的方法,实际上既可以被类直接调用也可以被类的实例对象调用,但是被实例对象调用的时候,要求方法至少有一个参数,而且调用时会将实例对象本身传给第一个参数。

 
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')
  
    
>>> Student.sayHello
<function Student.sayHello at 0x02AC7810>
>>> a = Student('Bob')
>>> a.sayHello
<bound method Student.sayHello of <__main__.Student object at 0x02AD03F0>>

>>> Student.sayHello('en') # 类调用的时候,将'en'传给了lang参数
en
Welcome!

>>> a.sayHello() # 类实例对象调用的时候,将对象本身自动传给了lang参数,不能再接收参数
<__main__.Student object at 0x02AD03F0>
你好!

  >>> a.sayHello('en')
  Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
  a.sayHello('en')
  TypeError: sayHello() takes 1 positional argument but 2 were given


  

  2. staticmethod函数功能就是将一个方法定义成类的静态方法,正确的方法是使用 @staticmethod装饰器,这样在实例对象调用的时候,不会把实例对象本身传入静态方法的第一个参数了。

 
# 使用装饰器定义静态方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')

            
>>> Student.sayHello('en') #类调用,'en'传给了lang参数
en
Welcome!

>>> b = Student('Kim') #类实例对象调用,不再将类实例对象传入静态方法
>>> b.sayHello()
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    b.sayHello()
TypeError: sayHello() missing 1 required positional argument: 'lang'

>>> b.sayHello('zh')  #类实例对象调用,'zh'传给了lang参数
zh
你好!
原文地址:https://www.cnblogs.com/wyzhou/p/9595667.html