本章主要说明那些被内建到解释器的标准类型,主要的有数值,序列,映射,类,实例,例外。
一些运算符被多种类型支持,实际上所有的类型都可以被比较,检验真假,转换成字符串(repr(),str()后者会被print隐式调用,str的返回和只有第一个参数的print一样)。
因此下文首先介绍这些被支持的运算,之后介绍内置类型数值,序列,映射,类,实例,例外。
运算
真值检验,布尔值运算,比较
真值检验
默认的一个对象被认为是True,除非这个类定义了返回False的__bool__()方法或者是返回0的__len__()。
class Bealoonfalse():
def __bool__(self):
return False
def __index__(self):
return 2
pass
class Booleantrue:
pass
class Comp:
def __le__(self, other):
return True
class Comp1:
def __init__(self,a):
self.a = a
def __ge__(self, other):
if self.a ==0:
return False
else:return NotImplemented
t = Booleantrue()
f = Bealoonfalse()
c = Comp()
c10 = Comp1(0)
c11 = Comp1(1)
print(bool(t),bool(f),bin(f),hex(f))#True False 0b10 0x2
print(t==f)# false不报错
print(t>f)#报错没有方法__lt__(), __le__(), __gt__(), and __ge__(),无法比大小
print(c<=1)# c定义了__le__(),返回true
print(c10>=c,c11>=c) #首先调用前面操作数的__ge__,返回Notimplemented在调用后面操作数的__le__ 方法。
下面列举大部分false的内置对象:
被认为是false的常量:None False
各种数值类型的0: 0,0.0,Decimal(0)
空的序列和集合:[],(),{}
布尔值运算符–and or not
短路运算
x or y: if x is false,then y,else x 短路运算符,就是说如果x为true就不里y了
x and y :if x is false, then x, else y。短路运算符
not x:if x is false, then True, else False。not的优先运算级比非布尔值运算的运算符低,如not a = = b等价于not(a = = b);而a == not b 是语法错误。
比较
boolean运算符,运算优先级相同,任意相连如a< b >ca< b and b>c and c<z(主要and是短路运算)。
大于啥的不说了
!= 不等于;is id相同;is not id不同。
说明:
1,不同了类型除了(不同数值类型),不会= =;不同类型(内部没有定义order方法的)的比较(大于小于)会报错。
2,不同id的实例不会= =除了其类中定义了__eq__()方法。
3,一个实例不能与本类实例或者是其他类型实例比较大小(不是= =和!=),除非定义了order方法:lt(), le(), gt(), and ge().
4,is ,is not不会报错,但也不能自定义
5,还有两种运算符,in和not in支持iterable或者执行__contains__方法的。
内部类型
这些都适用布尔运算。
数值类型们 int,float,complex(不是一种类型)
有三种数值类型整数,浮点型和复数,另外,布尔类作为int的子类。
int无限精确度(二进制数表示整数不会约等于);
而浮点型(1.1转成2进制,就不得不有精确的了),float是用C的double实现的,关于精确度可以在sys.float_info查看,返回一个tuple。
inport sys
sys.float_info[0]
1.7976931348623157e+308
复数的实虚部分都是浮点类型。数字字面值如(1,1.0)后加J或者j,产生一个复数的虚部。
注意在声明复数虚部时字母j或J前必须跟一个数值字面值(int,flaot)。
此外Python支持混合运算如,1+1.0:会把1转成float计算,而1.0+1J:会把1.0转成复数;数值类型的比较也遵循这种规则。(而如后文提到的bytes-like对象的混合运算和set、frozenset的混合运算,返回值的类型与操作符前面的操作数相同)
所有的(除了complex)都支持一下操作符以优先度递增排列、
notes:
1.//做除法后,对商取整(以数值最小为标准),如-1//2,商为-0.5,取整-1或者0,-1<0,所以答案为-1.
2,complex不可用,复数不可求余数,其他都支持。
3,round或者直接取整数部分,具体看math.floorhe math.ceil.
4.float接受字符串‘nan’,‘inf’和‘+’,‘-’
5.0**0等于1
6.对于数值类型的构建函数,0-9数字或者相应的unicode值组成的数字字面值都可以接受。int(b’1’)
int和float还支持以下操作:
操作 | 结果 |
---|---|
math,trunc(x) | 截取整数部分 |
round(x,[,n]) | 保留n位小数,x会约等于最接近的y*10**(-n),y为整数,结果取y,两个y值,取偶数y |
math.floor(x) | 取整结果<=x |
math.ceil | 取整>=x |
对round举个例子。
当然这得看你的python版本,哎我的是3.6
round(1.5),取2
round(0.5)取0
然而round(2.675, 2) 取2.67,为什么呢,因为上文说过(电脑是无法精确表示浮点值的原因上面有),看是2.675,电脑眼里他就比2.675小一点一点,round后取最近的就变成了2.67了。因此建议,用round看场合。
int的位运算
只适用于int,计算优先级比数值计算±之类的低,高于比较与运算;但~和(y+x ,x-y)优先级一样
~1+2
0
(~1)+2
0
~(1+2)
-4
优先级递增。
1,n不可以为负,提起valueerror
2,相当于不检查溢出的x*pow(2,n)
3,相当于不检查溢出的x/pow(2,n)
4,Performing these calculations with at least one extra sign extension bit in a finite two’s complement representation (a working bit-width of 1 + max(x.bit_length(), y.bit_length()) or more) is sufficient to get the same result as if there were an infinite number of sign bits.
溢出错误:
当计算结果过大时,会提出这个错误,int一般不会提出溢出错误而胡思memoryerror,因为历史原因,溢出错误会被在需求之外的int提起;因为c缺少标准的福地安置错误处理,大多数float计算不会被检查。
int的其他方法
int执行抽象类number.Integral,除外提供其他方法。
int.bit_length()
返回int二进制除了符号和前缀的的长度。
n = -37
bin(n)
n.bit_length()#6
*int.to_bytes(length, byteorder, , signed=False)
返回代表int的字节列
length:有几个字节表示,长度不够表示的溢出错误
byteorder:‘big’正常顺序,‘‘small’’反过来
signed:当int为负数,只应该声明为True,数值是正数的byte的每一位被15(f)减。
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'
*classmethod int.from_bytes(bytes, byteorder, , signed=False)
>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680
float的其他方法
float类执行抽象类numbers.Real,float还定义了如下方法:
float.as_integer_ratio():
返回(int1,int2),int1/int2==float,符号一直在int1上。有无限大提出overflowerror,NaNs,valueerror。
**float.is_integer():**例如
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
python数值内部用二进制储存,所以转换成浮点型或是从一个小数字符串常常有小的约等于的错误,而16进制的字符串可以精密的表示浮点数,这个可以用来debug和做数值工作。下面两个方法,
float.hex()
注意和内置方法hex()比较,int的hex形式用hex(int)获取。
返回的字符串0x开头,p和指数结尾。
形式如下
[sign] ['0x'] integer ['.' fraction] ['p' exponent]
,
>>> float.fromhex('0x3.a7p10')
3740.0
(3 + 10./16 + 7./162) * 2.010, or 3740.0:a就是10
classmethod float.fromhex(s)
>>> float.hex(3740.0)
'0x1.d380000000000p+11'
数值类型们的哈希值hash()是如何计算的
(int,fraction.Fraction;和有限的float,有限的decimal.Decimal)类型的x,y在比较时,其实都是hash(x)和hash(y)比较。
P = sys.hash_info.modulus,机器位数62,32;P=2*(62[32]-1)-1,上面还提到过sys.float_info)*
hash(x)的规则如
import sys, math
def hash_fraction(m, n):
"""Compute the hash of a rational number m / n.
Assumes m and n are integers, with n positive.
Equivalent to hash(fractions.Fraction(m, n)).
"""
P = sys.hash_info.modulus#P值
# Remove common factors of P. (Unnecessary if m and n already coprime.)
while m % P == n % P == 0:
m, n = m // P, n // P
if n % P == 0:
hash_value = sys.hash_info.inf
else:
# Fermat's Little Theorem: pow(n, P-1, P) is 1, so
# pow(n, P-2, P) gives the inverse of n modulo P.
hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
if m < 0:
hash_value = -hash_value
if hash_value == -1:
hash_value = -2
return hash_value
def hash_float(x):
"""Compute the hash of a float x."""
if math.isnan(x):
return sys.hash_info.nan
elif math.isinf(x):
return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
else:
return hash_fraction(*x.as_integer_ratio())
def hash_complex(z):
"""Compute the hash of a complex number z."""
hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
# do a signed reduction modulo 2**sys.hash_info.width
M = 2**(sys.hash_info.width - 1)
hash_value = (hash_value & (M - 1)) - (hash_value & M)
if hash_value == -1:
hash_value = -2
return hash_value
迭代器类型
container._ iter _():返回一个iterator
iterator必须有以下方法:
iterator._ iter ():
返回iterator自身
iterator. next _():他被要求准许容器和迭代器可以和for,in语句一起使用。
返回容器中下一个的元素,如果没有了提出stopiterator exceptions。
Once an iterator’s next() method raises StopIteration, it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.
生成器
生成器更加便利的执行interator协议,container._ iter ()作为生成器,会自动返回一个iterator对象(应该说是生成器,他提供了 iter ()和 next _)
序列类型-list tuple range
常见序列操作
优先度递增排序,之后优先级会进行整理这里不再赘述