Python异常处理机制:try-except -else-finally:
{相当于Java的try-catch}
try: num1 = int(input("请输入第一个数:")) num2 = int(input("请输入第二个数:")) sum = num1 / num2 except ZeroDivisionError as e: print('分母不能为0!') print(e) except ValueError as e: print('请输入int型数据') print(e) #invalid literal for int() with base 10: 'q' else: print('sum=', sum) finally: print('无论有没有出现异常都会执行') ''' traceback模板打印异常信息 ''' import traceback try: print('=============================')# 位置会改变 print(10/0) except : traceback.print_exc()
Python中一切皆对象
与Java中一致,与Java不同的是,,类名不一定要与file名称一样
类的组成:类的属性,实例方法,静态方法,类方法
类的__init__(self)方法用于创建的对象进行初始化
class Student: native_place='江西理工' #类属性 def __init__(self,name,age): #name,age为实例属性 self.name=name #self.name 称为实例属性,进行了一个赋值操作,将局部变量的name赋值给实例属性 self.age=age print("哈哈哈哈") #实例方法 def ff(self): print("这是一个实例方法") #类方法 @classmethod def cm(clsc): print("这是一个类方法") #静态方法 @staticmethod def sm(): print("这是一个静态方法") def show(): print("这是一个函数") print(id(Student)) #1867676104832 print(type(Student)) #<class 'type'> print(Student) #<class '__main__.fun'> #类的对象的调用 stu=Student("张三",15) stu.ff()#Student.ff(stu) stu.gender='女' #动态绑定属性 print(id(stu)) print(type(stu)) print(stu.native_place) print(stu.gender) stu.show=show #动态绑定方法 stu.show()
面向对象的三大特征:封装,继承,多态
封装:self.__age=age(加两个下划线).在外部使用封装:stu._Student__age
继承:class 子类类名(父类1,父类2)
class Student: def __init__(self,name,age): self.name=name self.__age=age #封装 def show(self): print(self.name,self.__age) stu=Student('张三',19) stu.show() print(stu.name) print(dir(stu)) print(stu._Student__age) class Person(object): def __init__(self,name,age): self.name=name self.age=age def info(self): print(self.name,self.age) class Student1(Person): def __init__(self,name,age,stuno): super().__init__(name,age) self.stuno=stuno class Teacher(Person): def __init__(self,name,age,teachno): super().__init__(name,age) self.teachno=teachno stu1=Student1("小米",16,20) stu1.info()
属性:1.dict:获得类对象或实例对象所绑定的所有属性和方法的字典
方法:1.len():通过重写_len_()方法,让内置函数len()的参数可以是自定义类型
2.add():通过重写_add_()方法,课使用自定义对象有“+”功能,重写可以是字符串的相加链接
3.new():用于创建对象
4.init():对创建的对象进行初始化
class A: pass class B: pass class C(A,B): def __init__(self,name,age): self.name=name self.age=age def __add__(self, other): return self.name+other.name x1=C("kk",21) #x为实例对象 print(x1.__dict__) #{'name': 'kk', 'age': 21} print(C.__dict__) #{'__module__': '__main__', '__init__': <function C.__init__ at 0x0000013924A6E790>, '__doc__': None} a=10 b=20 c=a.__add__(b) print(c) #30 x2=C("ss",18) print(x1.__add__(x2)) #kkss class Person1: def __init__(self,name,age): print("__init__被调用执行了,self的id值为{0}".format(id(self))) self.name = name self.age = age def __new__(cls, *args, **kwargs): print("__new__被调用执行了,cls的id值为{0}".format(id(cls))) obj=super().__new__(cls) print("创建的对象的id值为{0}".format(id(obj))) return obj p=Person1("zz",15)
1.Python操作文件
2.打开或新建文件,创建文件对象:file=open(filename[,mode,encoding])
#mode:打开模式默认为只读,encoding:默认文本文件中字符的编写格式为gbk
3.读,写文件
4.关闭资源
file=open("a.txt","w") file.write("kkkk") file.close() #文件对象的常用方法 file1=open("b.txt","r") file1.seek(2) print(file1.read()) print(file1.tell()) #13 file1.close()
可以自动管理上下资源,不论声明原因跳出with块。都能确保文件正确的关闭,以此达到释放资源的目的
with open("b.txt","r") as file: print(file.read()) with open("背景.png","rb") as src_file: with open("logo.png","wb") as target_file: target_file.write(src_file.read()) #文件复制,不需要手动关闭
os:模块是Python内置的与操作系统功能和文件系统相关的模块,该模块中的语句执行结果通常与操作系统有关,
在不同的操作系统上运行,得到的结果可能不同
os与os.path模块用于对目录或文件进行操作
1.os模块操作目录相关函数
2.os.path模块操作目录相关函数
import os print(os.getcwd()) #D:\pycharm\workspace\NO4 import os.path print(os.path.abspath("Demo02.py")) print(os.path.exists("Demo01.py")) print(os.path.exists("Demo09.py")) print(os.path.join("NO4","Demo01.py")) #NO4\Demo01.py
import os filename = "students.txt" def main(): while True: menu() choice = int(input("请选择:")) if choice in [0, 1, 2, 3, 4, 5, 6, 7]: if choice == 0: answer = input("您确定要退出系统吗?y/n") if answer == "y" or answer == "Y": print("谢谢使用!!!") break else: continue elif choice == 1: print("录入学生信息") insert() elif choice == 2: print("查找学生信息") search() elif choice == 3: print("删除学生信息") delete() elif choice == 4: print("修改学生信息") modefy() elif choice == 5: print("排序") sort() elif choice == 6: print("统计学生总人数") total() elif choice == 7: print("显示所有学生信息") show() else: print("输入错误,请重新输入") def menu(): print("========================学生信息管理系统===================") print("--------------------------功能菜单-----------------------") print("\t\t\t\t1.录入学生信息") print("\t\t\t\t2.查找学生信息") print("\t\t\t\t3.删除学生信息") print("\t\t\t\t4.修改学生信息") print("\t\t\t\t5.排序") print("\t\t\t\t6.统计学生总人数") print("\t\t\t\t7.显示所有学生信息") print("\t\t\t\t0.退出") print("--------------------------------------------------------") if __name__ == '__main__': main()
def insert(): # 录入学生信息 studentList = [] while True: id = input("请输入学生学号(1001):") if not id: break name = input("请输入学生姓名:") if not name: break try: english = int(input("请输入学生英语成绩:")) python = int(input("请输入学生Python成绩:")) java = int(input("请输入学生Java成绩:")) except: print("输入无效,请重新输入") continue student = {"id": id, "name": name, "English": english, "Python": python, "Java": java} studentList.append(student) save(studentList) print("学生信息录入完毕") answer = input("是否继续添加y/n") if answer == "y" or answer == "Y": continue else: print("谢谢使用!!!") break def save(lst): try: stu_txt = open(filename, "a+", encoding="utf-8") except: stu_txt = open(filename, "w", encoding="utf-8") for item in lst: stu_txt.write(str(item) + "\n") stu_txt.close()
def delete(): while True: student_id = input("请输入学生的ID:") if student_id != "": if os.path.exists(filename): with open(filename, "r", encoding="utf-8") as file: student_old = file.readlines() else: student_old = [] flag = False if student_old: with open(filename, "w", encoding="utf-8") as wfile: d = {} for item in student_old: d = dict(eval(item)) # 将字符串转换成字典 if d['id'] != student_id: wfile.write(str(d) + "\n") else: flag = True if flag: print(f"id为{student_id}的学生信息已删除") else: print(f"没有找到id为{student_id}的学生") else: print("无学生信息") break show() answer = input("是否继续删除y/n") if answer == "y" or answer == "Y": continue else: print("谢谢使用!!!") break
def search(): student_query=[] while True: id="" name="" if os.path.exists(filename): mode=input("按ID查询输入1,按姓名查询输入2:") if mode=='1': id=input("请输入学生ID:") elif mode=='2': name=input("请输入学生姓名:") else: print("您的输入有误") search() with open(filename, "r", encoding="utf-8") as rfile: student=rfile.readlines() for item in student: d=dict(eval(item)) if id!="": if d['id']==id: student_query.append(d) elif name!="": if d['name']==name: student_query.append(d) else: print("暂未保存学生信息") return
def modefy(): show() if os.path.exists(filename): with open(filename, "r", encoding="utf-8") as rfile: student_old = rfile.readlines() else: return student_id = input("请输入要修改的学员的ID:") with open(filename, "r", encoding="utf-8") as wfile: for item in student_old: d = dict(eval(item)) if d['id'] == student_id : print("找到学生信息,可以修改相关信息了!") while True: try: d['name'] = input("请输入学生姓名:") d['english'] = input("请输入学生英语成绩:") d['python'] = input("请输入学生Python成绩:") d['java'] = input("请输入学生Java成绩:") except: print("您的输入有误") else: break wfile.write(str(d) + "\n") print("修改成功") else: wfile.write(str(d) + "\t") answer = input("是否继续修改y/n") if answer == 'y' or answer == "Y": modefy()