实验目的及要求:
一、实验目的:
(1)掌握定义类及创建对象的基本方法,掌握类的继承语法。
(2)掌握Python中的运算符重载语法,理解魔法函数的用途。
(3)练习使用面向对象程序设计方法解决实际问题。
(4)熟悉文件系统的目录结构,掌握Python中文本文件的读取与写入方法。
(5)熟悉Excel文件、Json格式文件、及二进制文件的方法。
二、实验要求:
(1)完成实验课本15.1~15.4,17.1~17.5。
(2)使用Pycharm+Python或Pycharm+Anaconda或VSC完成程序编写、调试、运行,并将代码及运行结果截图整理成文档,形成实验报告,并总结心得体会。
实验内容:
15.1.py:
import random
class Dice:
def __init__(self,sides=6):
self.iSides = sides
self.results = []
def rollDice(self):
r = random.randint(1,self.iSides)
self.results.append(r)
return r
def sideCount(self,side):
return self.results.count(side)
def rollCount(self):
return len(self.results)
d = Dice()
print("-----Roll dice for 100 times-----")
for x in range(100):
r = d.rollDice()
if x < 10:
print(r,end=",")
print("...")
print("-----Statistics of rolling the dice-----")
for i in range(1,d.iSides+1):
sideCount = d.sideCount(i)
rollCount = d.rollCount()
print(f"Side {i}: {sideCount}/{rollCount} = "\
f"{sideCount*100/rollCount:.1f}%")
结果:
15.2.py:
class Pet:
def __init__(self,name):
self.__sName = name
def getName(self):
return self.__sName
class Rabbit(Pet):
def __init__(self,name):
Pet.__init__(self,name)
def speak(self):
print(f"Hello from rabbit {self.getName()}.")
def eat(self,iWeight):
print(f"Rabbit {self.getName()} ate {iWeight} gram's food.")
class Cat(Pet):
def __init__(self,name):
Pet.__init__(self,name)
def eat(self,iWeight):
print(f"Cat {self.getName()} ate {iWeight} gram's food.")
class DragonLi(Cat):
def __init__(self,name):
Cat.__init__(self,name)
def speak(self):
print(f"Hello from dragonli cat {self.getName()}.")
class Persian(Cat):
def __init__(self,name):
Cat.__init__(self,name)
def speak(self):
print(f"Hello from persian cat {self.getName()}.")
print("-------------Rabbit Charlie--------------")
r = Rabbit("Charlie")
r.eat(100)
r.speak()
print("-------------Cat Lucy--------------")
c1 = DragonLi("Lucy")
c1.eat(200)
c1.speak()
print("-------------Cat Eddie--------------")
c2 = Persian("Eddie")
c2.eat(100)
c2.speak()
print(isinstance(c1,Persian))
print(isinstance(c1,DragonLi))
print(isinstance(c1,Cat))
print(isinstance(c1,Pet))
print(isinstance(r,Pet))
print(isinstance(r,Rabbit))
print(isinstance(r,Persian))
结果:
15.3.py:
class Vector3D:
def __init__(self,x,y,z):
self.x,self.y,self.z = x,y,z
def __str__(self):
return str((self.x,self.y,self.z))
def __add__(self,v):
return Vector3D(self.x+v.x,self.y+v.y,self.z+v.z)
def __sub__(self,v):
return Vector3D(self.x-v.x,self.y-v.y,self.z-v.z)
def length(self):
return (self.x**2+self.y**2+self.z**2)**0.5
v1 = Vector3D(1,2,3)
v2 = Vector3D(4,5,6)
v3 = v1 + v2
v4 = v2 - v1
print("v1 =",v1)
print("Length of v1 =", v1.length())
print(f"{v1}+{v2}={v3}")
print(f"{v2}-{v1}={v4}")
结果:
15.4.py:
class Rect:
def __init__(self, tl, br):
self.tl, self.br = tl, br
def width(self):
t = self.br.x - self.tl.x
return t if t > 0 else -t
def height(self):
t = self.br.y - self.tl.y
return t if t > 0 else -t
def area(self):
return self.width() * self.height()
def topRight(self):
return Point(self.br.x,self.tl.y)
def bottomLeft(self):
return Point(self.tl.x,self.br.y)
def diagonalLength(self):
return self.br - self.tl
class Point:
def __init__(self,x,y):
self.x, self.y = x, y
def __sub__(self,p):
return ((self.x - p.x)**2 + (self.y - p.y)**2) ** 0.5
def __str__(self):
return str((self.x,self.y))
rt = Rect(Point(1,6),Point(7,8))
print("Vertices of rectangle rt:")
print(f"{rt.tl}-----------------------------{rt.topRight()}")
print(f"{rt.bottomLeft()}-----------------------------{rt.br}")
print("Size information of rectangle rt:")
print(f"width - {rt.width()}\theight - {rt.height()}")
print(f"area - {rt.area()}\tdiagonal length - "\
f"{rt.diagonalLength()}")
结果:
17.1.py:
f = open("abc.txt")
print("abc.txt: ",f.read())
f = open("d:\\pypractice\\t17_fileio\\abc.txt")
print("d:\\pypractice\\t17_fileio\\abc.txt: ",f.read())
f = open("../t21_cellcounter/cellcounter.py")
print("first line of cellcounter.py(1): ",f.readline())
f = open("d:/PyPractice/T21_CellCounter/CellCounter.py")
print("first line of cellcounter.py(2): ",f.readline())
结果:
17.2.py:
with open("AddLineNo.py","rt") as f:
lines = f.readlines()
maxLength = len(max(lines,key=len))
newLines = [line.rstrip().ljust(maxLength) + \
"#" +str(r+1) + "\n" for r,line in enumerate(lines)]
with open("AddLineNo2.py","wt") as f:
f.writelines(newLines)
结果:
17.3.py:
from openpyxl import load_workbook
workBook = load_workbook("ScoresSheet.xlsx")
workSheet = workBook.worksheets[0]
for idx,row in enumerate(workSheet.rows):
if idx==0:
continue
row[5].value = row[1].value * 0.3 + row[2].value * 0.1 \
+ row[3].value * 0.2 + row[4].value * 0.4
workBook.save("ScoresSheet2.xlsx")
结果:修改前
修改后:
17.4和17.5题:
years = [2020,2019,2018,2017,2016]
incomes = { '北京市':[5483.89,5817.10,5785.92,5430.79,5081.26],
'天津市':[1923.05,2410.41,2106.24,2310.36,2723.50],
'上海市':[7046.30,7165.10,7108.15,6642.26,6406.13],
'重庆市':[4257.98,4070.83,3911.01,3577.99,3388.85] }
import json
with open("IncomesData.json","w") as f:
json.dump([years,incomes],f)
with open("IncomesData.json") as f:
years1, incomes1 = json.load(f)
print("years1:",years1)
print("incomes1:",incomes1)
import os
print("json file size:",os.path.getsize("IncomesData.json"))
import pickle
with open("IncomesData.dat","wb") as f:
pickle.dump([years,incomes],f)
with open("IncomesData.dat","rb") as f:
years2, incomes2 = pickle.load(f)
print("years2:",years2)
print("incomes2:",incomes2)
import os
print("dat file size:",os.path.getsize("IncomesData.dat"))
结果: