流畅的Python

发布于 2018-03-12 · 本文总共 4577 字 · 阅读大约需要 14 分钟

format

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’ 使用方法由两种:b.format(a)和format(a,b)。

>>> print('{} {}'.format('hello','world'))  # 不带字段
hello world
>>> print('{0} {1}'.format('hello','world'))  # 带数字编号
hello world
>>> print('{0} {1} {0}'.format('hello','world'))  # 打乱顺序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world'))  # 带关键字
world hello world

进阶

(1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐

(2)取位数“{:4s}”、”“等

>>> print('{} and {}'.format('hello','world'))  # 默认左对齐
hello and world
>>> print('{:10s} and {:>10s}'.format('hello','world'))  # 取10位左对齐,取10位右对齐
hello      and      world
>>> print('{:^10s} and {:^10s}'.format('hello','world'))  # 取10位中间对齐
  hello    and   world   
>>> print('{} is {:.2f}'.format(1.123,1.123))  # 取2位小数
1.123 is 1.12
>>> print('{0} is {0:>10.2f}'.format(1.123))  # 取2位小数,右对齐,取10位
1.123 is       1.12

数据结构和算法

星号表达式在迭代元素为可变长元组的序列时是很有用

星号解压语法在字符串操作的时候也会很有用

a, *b, c = "hello jjjj hhh world".split()

迭代器、生成器

迭代器

想遍历一个可迭代对象中的所有元素,但是却不想使用for循环:

使用 next() 函数并在代码中捕获 StopIteration 异常

StopIteration:

>>> l = [1,2,3,4,5,6]
>>> it = iter(l)
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it)
5
>>> next(it)
6
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

定义一个 iter() 方法,将迭代操作代理到容器内部的对象上去:

class Node:
    def __init__(self, value):
        self._value = value
        self._children = []

    def __repr__(self):
        return 'Node({!r})'.format(self._value)

    def add_child(self, node):
        self._children.append(node)

    def __iter__(self):
        return iter(self._children)

生成器

实现一个自定义迭代模式

def frange(start, stop, increment):
    x = start
    while x < stop:
        yield x
        x += increment

for n in frange(0, 4, 0.5):
    print(n)

一个函数中需要有一个 yield 语句即可将其转换为一个生成器。 跟普通函数不同的是,生成器只能用于迭代操作。

常用函数

ceil(x) 取顶
floor(x) 取底
fabs(x) 取绝对值
factorial (x) 阶乘
hypot(x,y) sqrt(xx+yy)
pow(x,y) x的y次方
sqrt(x) 开平方
log(x)
log10(x)
trunc(x) 截断取整数部分
isnan (x) 判断是否NaN(not a number)
degree (x) 弧度转角度
radians(x) 角度转弧度

random

random.uniform(a,b): 用于生成一个指定范围内的随机浮点数,a,b为上下限

random.randint(a,b) 用于生成一个指定范围内的整数,a为下限,b为上限,生成的随机整数a<=n<=b

random.randrange([start], stop, [,step]) 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1

random.choice(sequence) 从序列中获取一个随机元素,参数sequence表示一个有序类型,并不是一种特定类型,泛指list,tuple,字符串等

random.shuffle(x[, random]) 用于将一个列表中的元素打乱

random.sample(sequence, k) 从指定序列中随机获取k个元素作为一个片段返回,sample函数不会修改原有序列

property

示例

#-*-coding=UTF-8-*-
class A(object):

    @property
    def birth(self):
        return self._v

    @birth.setter
    def birth(self,value):
        if value>2018:
            raise ValueError("error,max is 100")
        elif value < 1900:
            raise ValueError("min is 0")
        self._v = value

    @property
    def age(self):
        return 2018 - self._v


if __name__ == "__main__":
    s = A()
    s.birth = 1992
    print s.birth
    print s.age

HTTP

4. GET

r = requests.get(‘http://httpbin.org/get’)

4.1. 传参

payload = {'key1': 'value1', 'key2': 'value2', 'key3': None}
r = requests.get('http://httpbin.org/get', params=payload)

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3

r.text 返回headers中的编码解析的结果,可以通过r.encoding = ‘gbk’来变更解码方式 r.content返回二进制结果 r.json()返回JSON格式,可能抛出异常 r.status_code r.raw返回原始socket respons,需要加参数stream=True

4.2. 结果保存到文件

with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

4.3. 传递headers

>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)

传递cookies

url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=dict(cookies_are='working'))
 r.text

设置超时时间

import requests
from requests.exceptions import ReadTimeout

try:
    # 设置必须在500ms内收到响应,不然或抛出ReadTimeout异常
    response = requests.get("http://httpbin.org/get", timeout=0.5)
    print(response.status_code)
except ReadTimeout:
    print('Timeout')

获取Token

import requests
from requests.exceptions import ReadTimeout

BASEURL = ""
URI = BASEURL+""

class Client_(object):

    def __init__(self):
        self.header = {'name': 'jack'}
        self.data = {'name': 'jack'}

    def get_service_t(self):
        url = URI
        header = self.header
        body = self
        return self.req_(url,header,data=body)

    def role_t(self):
        url = URI
        header = self.header
        body = {}
        return self.req_(url,header,data=body)

    def get_key(self):
        url = URI
        header = self.header
        body = {}
        return self.req_(url,header,data=body)

    def get_user_t(self):
        url = URI
        header = self.header
        body = {}
        return self.req_(url,header,data=body)

    def req_(self,url,header,method,data):
        if method == "post":
            response = requests.post(url, header, data=data)
            return response


def time_out():
    try:
        # 设置必须在500ms内收到响应,不然或抛出ReadTimeout异常
        response = requests.get("http://httpbin.org/get", timeout=0.5)
        print(response.status_code)
    except ReadTimeout:
        print('Timeout')

if __name__ == "__main__":
  test_client = Client_()
  print test_client.get_service_t()



本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。
声明:
本博客欢迎转发,但请保留原作者信息!
博客地址:邱文奇(qiuwenqi)的博客;
内容系本人学习、研究和总结,如有雷同,实属荣幸!
阅读次数:

文章评论

comments powered by Disqus


章节列表