目录
global和nonlocal函数简介
global:将函数内部的函数变量return到主程序,其中必须要保证global放在函数体的内部
nonlocal:声明的变量不是局部变量,也不是全局变量,而是外部嵌套函数内的变量。
def scope_test():
def do_local():
# 此函数定义了另外的一个spam字符串变量,并且生命周期只在此函数内。此处的spam和外层的spam是两个变量,如果写出spam = spam + “local spam” 会报错
spam = "local spam"
def do_nonlocal():
nonlocal spam # 使用外层的spam变量
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignmane:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
output:
# After local assignmane: test spam
# After nonlocal assignment: nonlocal spam
# After global assignment: nonlocal spam
# In global scope: global spam
从代码和输出结果可以看出global函数申明的是所有函数以外的全局变量spam,nonlocal作用于嵌套函数的外层函数定义的变量spam,而内部函数如果没有nonlocal或者global申明是无法作用内部函数以外的区域的。【每一个函数内部都可以定义一个临时的变量,尽管外部总程序已经有了和这个临时变量同名的变量,而且函数内部如果有和外部同名的变量会优先调用局部的变量】
json介绍
json是一种存储和交换数据的写法,是由JavaScript对象标记书写的文本,是一种轻量级数据交换格式。详细介绍可以参考JSON
提示:在此只介绍json在python中最基本的用法。
1.json.dump(obj, fp) # obj为需要存储的变量,fp为存储的位置
2.json.load(fp) # fp为存储的位置
以下举例:
import json
filename = "username.json"
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What's your name?")
with open(filename, "w") as f:
json.dump(username, f)
print(f"we'll remember you when you come back,{username}")
else:
print(f'Welcome back {username}')
python的类的介绍
python类必须要知道的知识点
1.类的属性可以是任何的对象,可以是某个值,某个变量,甚至是某个对象。
2.__function()函数是内部的函数,不是对象的动作方法,因此无法从外面调用,同理self.__attribute是内部属性,在外面调用会报错。
下面我们根据一个例子来详细述说(该代码需要用到的文件已给):
# -- coding:utf-8 --
"""这个程序旨在寻找文件中的某个观测站在1月某号时站点的经纬度,当月的平均温度,当月的最高气温和最低气温"""
def judge(f, id, month):
"""这个函数是找出文件中id和month和我们输入的站台台号和观测日子对应的信息"""
f.seek(0)
for i in f:
mid = i.split()
if mid[0] == id and mid[6] == month:
return mid
def reading(file):
"""该函数是对我们输入的文件求所有站点的当月平均温度,当月最高气温和最低气温并返回给IN_THE_END这个全局变量"""
# 这里定义的全局变量IN_THE_END
global IN_THE_END
Cumulative = 0
temperature_sum = 0
IN_THE_END = []
for line in file:
if line[0:5] == "50434":
Cumulative += 1
if Cumulative == 1:
mid = line.split()
mid = [int(x) for x in mid]
Station_ID, lat, lon = mid[0:3]
temperature = mid[7]
temperature_max = mid[7]
temperature_min = mid[7]
temperature_sum += temperature
elif Cumulative < 14:
mid = line.split()
mid = [int(x) for x in mid]
temperature = mid[7]
if temperature < temperature_min:
temperature_min = temperature
elif temperature > temperature_max:
temperature_max = temperature
temperature_sum += temperature
if Cumulative == 13:
temperature_average = temperature_sum / 13
IN_THE_END.append((Station_ID, lat, lon, round(temperature_average, 3),
temperature_max, temperature_min))
Cumulative -= 13
temperature_sum = 0
else:
Cumulative += 1
if Cumulative == 1:
mid = line.split()
mid = [int(x) for x in mid]
Station_ID, lat, lon = mid[0:3]
temperature = mid[7]
temperature_max = mid[7]
temperature_min = mid[7]
temperature_sum += temperature
elif Cumulative < 32:
mid = line.split()
mid = [int(x) for x in mid]
year, month, day = mid[4:7]
temperature = mid[7]
if temperature < temperature_min:
temperature_min = temperature
elif temperature > temperature_max:
temperature_max = temperature
temperature_sum += temperature
if Cumulative == 31:
temperature_average = temperature_sum / 31
IN_THE_END.append((Station_ID, lat, lon, round(temperature_average, 3),
temperature_min, temperature_max))
Cumulative -= 31
temperature_sum = 0
class StationRecord:
"""这个类创建的对象能输出站点的经纬度,月平均气温,月最高温度和月最低温度"""
def __init__(self, inputid, fname, month):
self.lat = None
self.lon = None
self.mean_mon = None
self.min_mon = None
self.max_mon = None
self.id = inputid
self.month = month
self.f = fname
def latitude(self):
mid = judge(self.f, self.id, self.month)
self.lat = mid[1]
def longitude(self):
mid = judge(self.f, self.id, self.month)
self.lon = mid[2]
def mean_month(self):
mid = judge(self.f, self.id, self.month)
for line in IN_THE_END:
if str(line[0]) == mid[0]:
self.mean_mon = line[3]
def min_month(self):
mid = judge(self.f, self.id, self.month)
for line in IN_THE_END:
if str(line[0]) == mid[0]:
self.min_mon = line[4]
def max_month(self):
mid = judge(self.f, self.id, self.month)
for line in IN_THE_END:
if str(line[0]) == mid[0]:
self.max_mon = line[5]
def output_everything(self):
print(self.lat, self.lon, self.mean_mon, self.min_mon, self.max_mon, end=" ")
inputid = input("请输入站台的台号")
fname = open(r"C:\Users\lvyih\Desktop\station-chapter4.txt")
month = input("请输入站台观测的日子")
IN_THE_END = []
reading(fname)
# 这里要使用seek(0)的原因是读取完文件后指针在最后面,需要将指针放在前面,否则程序会出bug
fname.seek(0)
# 这里创建一个类的对象test然后输出我们想要的结果
test = StationRecord(inputid, fname, month)
test.longitude()
test.latitude()
test.mean_month()
test.min_month()
test.max_month()
test.output_everything()
补充:这个程序本意不是进行此类操作的,因此这些代码还有很多地方时不精简的,由于这只是个练习,我也不再对代码进行优化,里面用于举例的代码我大多用注释解释了,大家选择性读。
python类的继承和test类
test类
python中的test类是专门用于测试的类,需要import unittest
from name_function import get_formatted_name import unittest class NamesTestCase(unittest.TestCase): # 测试 name_function.py。 # 提示:其中要想在unittest.TestCase中的运行的函数一定要保证命名的前面是test打头,不然测试不会进行 def test_first_last_name(self): formatted_name = get_formatted_name('janis', 'joplin') self.assertEqual(formatted_name, "Janis Joplin") def test_first_last_middle_name(self): formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus') self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart') # 由于很多测试框架都会先导入测试文件再运行。而导入文件的同时,解释器会在导入的同时执行它。 if __name__ == "__main__": unittest.main()
其中unittest.TestCase是专门用来测试的类,以上用到了类的继承,继承了这个类之后定义的函数一定要保证命名的前面是以test打头,不然测试是不会进行的。test类中要进行申明判断,以下为比较常用的几个申明判断方法:
1.self.assertEqual(X, " ") # X是你想验证的变量,后面的字符串是要验证的是否相等
2.self.assertNotEqual(X, " ")
3.self.assertIn(X, Y) # 验证X在Y里面
4.self.assertNotIn(X, Y)
提示:我们进行类的测试和进行函数的测试没有很大差别,我们也可以选择到底是对单个类进行测试还是对整个模块进行测试
#########
关于__name__=="__main__"的讲解:
很多测试框架都会先导入测试文件再运行。但是在导入文件的同时,解释器就会在执行它。因此选择使用if __name__=="__main__"可以让程序只执行调用运行,不执行自身运行模块。
提示:类中的每一个方法都要加self参数,而__init__需要加self参数和输入的变量,其中属性可以在方法或者init中更改。
继承
类中如果需要使用继承,如果想要添加新的属性而不得不加上__init__的时候,我们可以使用super().__init__(...)来直接继承父类的所有属性(因为只要定义了__init__就意味着子类不使用父类的属性了,同理父类定义的方法子类可以用,但是如果子类定义了同名的新方法,那么只有新定义的方法有效,父类的该方法无效。)
python文件读取
我们根据一个例子将python读取文件最基本的方法进行讲述:
1.with open as 函数将文件打开,其中open参数中可以选择只读(“r”),写(“w”),追加(“a”)模式。
2.for i in file 可以直接遍历文件的每一行
3.file.readlines() 可以直接生成一个文件每一行内容(字符串)的列表【一次性读完】
4.file.readline() 就是一行一行地读
5.file.read() 把所有内容都读出来生成一个字符串(大多可以使用split(“\n”)来创建列表)
########
需要注意的点:
1.python写入文件的时候只能写入字符串
2.每读取一遍,指针需要重置,因此一定要学会用fname.seek(0)。
filename = "pi_digits.txt"
pi_string = ""
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
pi_string += line.strip()
print(pi_string[:50])
"""文件录入"""
filename = "programing.txt"
# 当要写入的时候Python会自动创建文件,w是写入,r是只读,a是追加;默认情况下python是以读取模式打开文件,如果要写入一定要定义"w"。
with open(filename, "w") as file_object:
file_object.write("I love programing.\n")
# Python只能将字符串放入文件当中,如果想要将数值放入文件当中的话,就要先用str()来转化一下。
with open(filename, "a") as file_object:
file_object.write("I also love programing.\n")
file_object.write("I can do anything\n")
file_object.write("I think I'm not strong enough,so let's improve myself and be stronger and be unstoppable.\n")
# 文件读取的时候,每读取一遍我们就要使用seek将光标重置才能再次读取