Python及单元测试

Tips of Python

2017-08-31  本文已影响1人  PPMac

Python的编码

  1. 为了处理英文字符,产生了ASCII码。
  2. 为了处理中文字符,产生了GB2312。
  3. 为了处理各国字符,产生了Unicode。
  4. 为了提高Unicode存储和传输性能,产生了UTF-8,它是Unicode的一种实现形式。
  5. Python2中默认的字符编码是ASCII码,未指定编码格式均按照ASCII编码处理。
  6. Python2中字符串有str和unicode两种类型。
  7. decode()方法将其他编码字符转化为Unicode编码字符
  8. encode()方法将Unicode编码字符转化为其他编码字符。
  9. Python 3的源码.py文件 的默认编码方式为UTF-8,所以在Python3中你可以不用在py脚本中写coding声明,并且系统传递给python的字符不再受系统默认编码的影响,统一为unicode编码。

with使用

来源 : https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/

with open(r'somefileName') as somefile:
    for line in somefile:
        print line
        # ...more code

这里使用了 with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后已经关闭了打开的文件句柄。如果使用传统的 try/finally 范式,则要使用类似如下代码:

somefile = open(r'somefileName')
try:
    for line in somefile:
        print line
        # ...more code
finally:
    somefile.close()

context

参考 : https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001478651770626de401ff1c0d94f379774cabd842222ff000

global

参考 : http://www.cnblogs.com/summer-cool/p/3884595.html
变量名解析:LEGB原则:
当在函数中使用未认证的变量名时,Python搜索4个作用域[本地作用域(L)(函数内部声明但没有使用global的变量),之后是上一层结构中def或者lambda的本地作用域(E),之后是全局作用域(G)(函数中使用global声明的变量或在模块层声明的变量),最后是内置作用域(B)(即python的内置类和函数等)]并且在第一处能够找到这个变量名的地方停下来。如果变量名在整个的搜索过程中
都没有找到,Python就会报错。


如果我可能在函数使用某一变量后又对其进行修改(也即再赋值),怎么让函数里面使用的变量是模块层定义的那个全局变量而不是函数内部的局部变量呢?这时候global修饰符就派上用场了。

hehe=6
def f():
    global hehe
    print(hehe)
    hehe=3
f()
print(hehe) 

在用global修饰符声明hehe是全局变量的hehe后(注意,global语句不允许同时进行赋值如global hehe=3是不允许的),上述输出是6和3,得到了我们想要的效果。

theading

参考 : http://www.jianshu.com/p/f61f39345f27 http://www.jianshu.com/p/a82bcb776cfa

#coding=utf-8
import time
import threading
import random
MONEY = 0#全局变量MONEY
gLock = threading.Lock()#锁
#生产者
def procuder():
    global MONEY#声明一个全局变量
    rand_money = random.randint(10,100)#随机生产一个数值
    gLock.acquire()#用acquire()申请锁
    MONEY += rand_money
    gLock.release()#释放锁
    print '生产者%s-生产了:%d' % (threading.current_thread, MONEY)
    time.sleep(2)#睡眠

#消费者
def customer():
    global MONEY #声明一个全局变量
    rand_money = random.randint(10,100)#随机生成一个数值
    if MONEY > rand_money:
        print '消费者%s-消费了:%d' %(threading.current_thread,rand_money)
        gLock.acquire()#加锁
        MONEY -= rand_money
        gLock.release()#释放
    else:
        print '需要消费的钱为:%d,余额为:%d' %(rand_money,MONEY)
if __name__ == "__main__":
    while True:
        procuder()
        customer()

如何在Python中使用static、class、abstract方法

类方法,实例方法,@classmethod

fomat格式化字符串

参考: https://www.2cto.com/kf/201312/262068.html

字符串的参数使用{NUM}进行表示,0, 表示第一个参数,1, 表示第二个参数, 以后顺次递加;
使用":", 指定代表元素需要的操作, 如":.3"小数点三位, ":8"占8个字符空间等;
还可以添加特定的字母, 如:
'b' - 二进制. 将数字以2为基数进行输出.
'c' - 字符. 在打印之前将整数转换成对应的Unicode字符串.
'd' - 十进制整数. 将数字以10为基数进行输出.
'o' - 八进制. 将数字以8为基数进行输出.
'x' - 十六进制. 将数字以16为基数进行输出, 9以上的位数用小写字母.
'e' - 幂符号. 用科学计数法打印数字, 用'e'表示幂.
'g' - 一般格式. 将数值以fixed-point格式输出. 当数值特别大的时候, 用幂形式打印.
'n' - 数字. 当值为整数时和'd'相同, 值为浮点数时和'g'相同. 不同的是它会根据区域设置插入数字分隔符.
'%' - 百分数. 将数值乘以100然后以fixed-point('f')格式打印, 值后面会有一个百分号.

age = 25  
name = 'Caroline'  
  
print('{0} is {1} years old. '.format(name, age)) #输出参数  
print('{0} is a girl. '.format(name))  
print('{0:.3} is a decimal. '.format(1/3)) #小数点后三位  
print('{0:_^11} is a 11 length. '.format(name)) #使用_补齐空位  
print('{first} is as {second}. '.format(first=name, second='Wendy')) #别名替换  
print('My name is {0.name}'.format(open('out.txt', 'w'))) #调用方法  
print('My name is {0:8}.'.format('Fred')) #指定宽度 

输出:

Caroline is 25 years old.   
Caroline is a girl.   
0.333 is a decimal.   
_Caroline__ is a 11 length.   
Caroline is as Wendy.   
My name is out.txt  
My name is Fred

eval的使用

可以把list,tuple,dict和string相互转化。

#################################################
字符串转换成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(b)
<type 'list'>
#################################################
字符串转换成字典
>>> a = "{1: 'a', 2: 'b'}"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
{1: 'a', 2: 'b'}
>>> type(b)
<type 'dict'>
#################################################
字符串转换成元组
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
>>> type(b)
<type 'tuple'>
上一篇下一篇

猜你喜欢

热点阅读