全局变量和局部变量
- global
- nonlocal
global 声明全局变量7
nonlocal想要修改外层函数变量的值。
调试
1)print
2)assert
断言n!=0,若n=0,则会触发AssertionError
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
foo('0')
3)logging
# coding=utf-8
__author__ = 'liu.chunming'
import logging
logging.basicConfig(level=logging.WARNING,
filename='D://log.txt',
filemode='w',
format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
# use logging
logging.info('this is a loggging info message')
logging.debug('this is a loggging debug message')
logging.warning('this is loggging a warning message')
logging.error('this is an loggging error message')
logging.critical('this is a loggging critical message')
单元测试
# -*- coding: utf-8 -*-
import unittest
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def get_grade(self):
if self.score > 100 or self.score < 0:
raise ValueError("分数只能在1-100")
if self.score >= 80:
return 'A'
if self.score >= 60:
return 'B'
return 'C'
class TestStudent(unittest.TestCase):
def test_80_to_100(self):
s1 = Student('Bart', 80)
s2 = Student('Lisa', 100)
self.assertEqual(s1.get_grade(), 'A')
self.assertEqual(s2.get_grade(), 'A')
def test_60_to_80(self):
s1 = Student('Bart', 60)
s2 = Student('Lisa', 79)
self.assertEqual(s1.get_grade(), 'B')
self.assertEqual(s2.get_grade(), 'B')
def test_0_to_60(self):
s1 = Student('Bart', 0)
s2 = Student('Lisa', 59)
self.assertEqual(s1.get_grade(), 'C')
self.assertEqual(s2.get_grade(), 'C')
def test_invalid(self):
s1 = Student('Bart', -1)
s2 = Student('Lisa', 101)
with self.assertRaises(ValueError):
s1.get_grade()
with self.assertRaises(ValueError):
s2.get_grade()
if __name__ == '__main__':
unittest.main()
文件操作
def read_file(dir1):
with open(dir1, "r", encoding="utf-8", errors="ignore") as f:
for line in f.readlines():
print(line)
def write_file(dir1):
with open(dir1, "a") as f:
f.write("i am a big orange\n")
dir2 = r"D://log.txt"
write_file(dir2)
read_file(dir2)
StringIO和BytesIO
from io import StringIO
f=StringIO()
f.write("hello")
print(f.tell())
f.seek(0)
print(f.readline())
# 上面两行可以替换为
print(f.getvalue())
f1 = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s=f1.readline()
print(s)
if s == '':
break
OS模块
序列化
pickle
把变量从内存中变成可存储或传输的过程称之为序列化
import pickle
import os
d = {"a": 1, "b": 0}
path = os.path.join(os.path.abspath('.'), "11.pkl")
with open(path, "wb") as f:
pickle.dump(d, f)
with open(path, "rb") as f:
print(pickle.load(f))
json
将对象序列化为json和将json反序列化为对象
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
# 将对象序列化为json
# print(json.dumps(s, default=lambda obj: obj.__dict__))
json_str = json.dumps(s.__dict__)
print(json_str)
def dict2student(d):
return Student(d['name'], d['age'], d['score'])
# 把json还原成object对象
s = json.loads(json_str, object_hook=dict2student)