【python基础】整理笔记(3)

前续:

【python基础】整理笔记(1)

【python基础】整理笔记(2)

10.3.7 使用多个文件
将上一个程序的代码移到一个函数中

def count(file):
try:
	with open('xxx.txt') as file_object:    
	    contents = file_object.read()
except FileNotFoundError:
	print("Sorry,the file xxx.txt does not exist!")  
else:
	words = contents.split()
	num = len(words)
    print(num)  
file = 'xxx.txt'
count(file)

10.4 存储数据
使用json模块将数据存储到文件中,并在程序再次运行加载该文件的数据。
10.4.1 使用json.dump()json.load()

import json 
n = [2,3,4,5,6,7]
file = 'xxx.json'
with open(file,w) as file_object:
	json.dump(n,file_object)
#会在改代码所在的文件夹中创建一个xxx.json的文件,里面存储上述列表
import json
file = 'xxx.json'
with open(file) as file_object:
	n = json.load(file_object)
print(n)
输出:
[2,3,4,5,6,7]

10.4.2 保存和读取用户生成的数据

import json
name = input("你的名字:")
file = 'xxx.json'
with open(file,'w') as file_object:
	json.dump(name,file_object)
	print("你好," + name + "你已经成功储存了你的信息。")
输出:
你的名字:曹操
你好,曹操你已经成功储存了你的信息。	
import json
file = 'xxx.json'
with open(file) as file_object:
	name = json.load(file_object)
print(name)
输出:
曹操

将两个代码使用 try-except-else函数合成一个

import json
file = 'xxx.json'
try:
	with open(file) as file_object:
	    name = json.load(file_object)
except FileNotFoundError:
	name = input("你的名字:")
	with open(file, 'w') as file_object:
		json.dump(name, file_object)
		print("你好," + name + "你已经成功储存了你的信息。")
else:
	print(name)

10.4.3 重构
将它化为一个具体的函数

import json
def user_name():
    file = 'xxx.json'
    try:
	    with open(file) as file_object:
	        name = json.load(file_object)
    except FileNotFoundError:
	    name = input("你的名字:")
	    with open(file, 'w') as file_object:
		    json.dump(name, file_object)
		    print("你好," + name + "你已经成功储存了你的信息。")
    else:
	    print(name)
user_name()

要是想进一步优化,可以重构user_name()这个函数,将获取的用户名储存在另一个函数中

import json
def get_username():
    """ 如果储存了用户名,就获取它 """
    file = 'xxx.json'
    try:
        with open(file) as file_object:
            name =json.load(file_object)
    except FileNotFoundError:
        return None
    else:
        return name
def user_name():
    """ 问候用户,并指出名字 """
    name = get_username()
    if name:
        print("你好," + name + "欢迎回来。")
    else:
        name = input("你的名字:")
        file = 'xxx.json'
        with open(file,'w') as file_object:
            josn.dump(name,file_object)
            print("你好," + name + "你已经成功储存了你的信息。")
user_name()

第十一章 测试代码

11.1 测试函数
最简单方法,直接在创建 xxx.py,将函数导入保存,然后在另一个项目中导入,运用输入
例:建立一个names.py

def name(first_name,last_name):
    #将姓和名连起来
    names = first_name + ' ' + last_name
    return names.title()

再建立一个项目

from names import name
#或者 import names
first_name = input("姓:")
last_name = input("名:")
my_name = name(first_name,last_name)
#my_name = names.name(first_name,last_name)
print(my_name)

11.1.1 单元测试
Python标准库中 unittest模块提供了代码测试工具。
doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。

import unittest
from names import name
class NamesTestCase(unittest.TestCase):
    """测试name_function.py"""
    def test_first_last_name(self):
        """能够正确地处理像Janis Joplin这样的姓名吗?"""
        formatted_name = name('janis', 'joplin')
        self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()

输出:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

此时说明测试可通过
若测试未通过

`E
======================================================================
ERROR: test_first_last_name (__main__.NamesTestCase)
能够正确地处理像Janis Joplin这样的姓名吗?
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:/代码存放/11.1.2.py", line 7, in test_first_last_name
    formatted_name = get_formatted_name('janis', 'joplin')
NameError: name 'get_formatted_name' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

11.2 测试类
unittest.TestCase类提供了很多断言方法。

下表 unittest Module中中的的断言方法

方法用途
assertEqual(a, b)核实a == b
assertNotEqual(a, b)核实a != b
assertTrue(x)核实x 为True
assertFalse(x)核实x 为False
assertIn(item , list )核实 item 在 list 中
assertNotIn(item , list )核实 item 不在 list 中

11.2.1类的测试
类的测试与函数的测试相似——你所做的大部分工作都是测试类中方法的行为,但存在一些不同之处,下面来编写一个类进行测试。来看一个帮助管理匿名调查的类:

survey.py

class AnonymousSurvey():
	"""收集匿名调查问卷的答案"""
	def __init__(self, question):
		"""存储一个问题,并为存储答案做准备"""
		self.question = question
		self.responses = []
	def show_question(self):
		"""显示调查问卷"""
		print(question)
	def store_response(self, new_response):
		"""存储单份调查答卷"""
		self.responses.append(new_response)
	def show_results(self):
		"""显示收集到的所有答卷"""
		print("Survey results:")
		for response in responses:
		print('- ' + response)

对类使用 unittest 模块测试

import unittest
from survey import AnonymousSurvey
class TestAnonmyousSurvey(unittest.TestCase):
      """针对AnonymousSurvey类的测试"""
      def test_store_single_response(self):
          """测试单个答案会被妥善地存储"""
          question = "What language did you first learn to speak?"
          my_survey = AnonymousSurvey(question)
          my_survey.store_response('English')
          self.assertIn('English', my_survey.responses)
unittest.main()
输出:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

对于Python基础的整理笔记就写到这里,其中有很多不足的地方,以后会不断改进。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值