0
点赞
收藏
分享

微信扫一扫

流畅的python 阅读笔记(第一章下)


第一章(下) 特殊方法

1、尽量使用内置函数,如:len、iter、str等,它们能调用特殊方法,而且速度更快

for i in x 背后实际采用的就是iter(x)

2、各个%的含义

%s 输出字符串

%f 浮点数

%d 输出整数(十进制)

%10.3s :7个空格+字符串前3

%10.3f:预留10个位置,留三个小数

%o 输出整数(八进制)

%.3s : 字符串前三

%06d 整数不足六位前面补0

%x输出整数(十六进制)

“%.*s” % (4,”lalala”):字符串前四

%r 任意格式

bin(x) 输出二进制

3、hypot() 函数

from math import hypot

hypot() 返回欧几里德范数 sqrt(x*x + y*y)。

4、bool() 函数,以下是false的情况

为0的数字,包括0,0.0

空字符串,包括”,”“

表示空值的None

空集合,包括(),[],{}

其他的值都认为是True

5、repr() 函数,相当于java里面的 toString()

6、complex() 函数返回复数

7、hash() 函数返回固定长度的hash值,可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary

8、index() 查找子字符串的位置

9、int() 显示数的不同进制

10、s.count(x) 计算s中x的个数,对象或字符串都可以

以下是书中介绍的vertor向量对象的构建过程:

from math import hypot

class Vector:

def __init__(self, x=0, y=0):

self.x = x;

self.y = y;


def __repr__(self):

return 'Vector(%r, %r)' % (self, self.y)


def __abs__(self):

hypot(self.x, self.y)


def __bool__(self):

return bool(abs(self))


def __add__(self, other):

x = self.x + other.x

y = self.y + other.y

return Vector(x, y)


def __mul__(self, scalar):

return Vector(self.x * scalar, self.y * scalar)

举报

相关推荐

0 条评论