Python之类、异常处理总结

作者: ropon 分类: Python 发布时间: 2018-11-03 14:31
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/10/26 11:17
# @Author  : Ropon
# @File    : 26_01.py

# 选课作业
# total_course_list = []
#
# class Course:
#     def __init__ (self,name,price,period):
#         self.name = name
#         self.price = price
#         self.period = period
# class Student:
#
#     func_list = [
#         {'text':'选课','name':'select_course'},
#         {'text':'查看课程','name':'show_selected_course'},
#         {'text':'删除课程','name':'show_del_course'},
#     ]
#
#     def __init__ (self,name):
#         self.name = name
#         self.courses = []
#     def select_course(self):
#         for i,item in enumerate(total_course_list,1):
#             print(i,item.name,item.price,item.period)
#         num = int(input('请选择要选择的课程'))
#         num = num - 1
#         course_obj = total_course_list[num]
#         if course_obj not in self.courses:
#             self.courses.append(course_obj)
#
#     def show_selected_course(self):
#         print('查看课程')
#     def show_del_course(self):
#         print('删除课程')
#
# def run():
#
#     for i in range(1,6):
#         obj = Course('课程-%s'%i, 90, 90)
#         total_course_list.append(obj)
#
#     stu_name = input('请输入学生姓名')
#     stu = Student(stu_name)
#
#     while True:
#         for i, item in enumerate(stu.func_list, 1):
#             print(i, item['text'])
#         num = int(input('请选择要执行的功能序号:'))
#         num = num-1
#         row = stu.func_list[num]
#         name = row['name']
#         func = getattr(stu,name)
#         func()
#
# if __name__ == '__main__':
#     run()

# 面向对象
#     - 三大特性
#         - 继承
#             - 单继承
# class A(object):
#     pass
# class B(A):
#     pass
#             - 多继承
# class A(object):
#     pass
# class B(object):
#     pass
# class C(A, B): # 先找左再找右
#     pass
#             -super() # 调用父类的方法)
# class A(object):
#     a = 11
#     b = 22
#     def f1(self):
#         print(self.a)
# class B(object):
#     a = 33
#     c = 44
# class C(A, B): # 先找左再找右
#     b = 222
#     def f2(self):
#         super().f1()
# obj = C()
# obj.f2()
#         - 封装
#             - 数据封装
# class A(object):
#     def __init__(self, a, b):
#         self.a = a
#         self.b = b
# obj = A(1, 2)
# print(obj.b)
#             - 方法封装

#         - 多态
#             - 鸭子模型
#     - 成员
#         - 变量
#             - 实例变量
# class A(object):
#     def __init__(self, a):
#         self.a = a
#             - 类变量
# class A(object):
#     a = 11
#         - 方法
#             - 实例方法
# class A(object):
#     def f1(self):
#         pass
#             - 类方法
# class A(object):
#     @classmethod
#     def f2(cls):
#         pass
#             - 静态方法
# class A(object):
#     @staticmethod
#     def f3(a, b):
#         return a, b
#             -特殊方法
#         - 属性
#             - @property
# class A(object):
#     @property
#     def start(self):
#         return 'start is ok'
# obj = A()
# print(obj.start)
#     - 修饰符
#         - 私有
#             - 编写 变量和方法前加两个下划线_
#         - 公有
#     - 内置函数
#         - issubclass()
#         - isinstance()
#         - type()
#         - callable()
#     - 反射
#         - getattr()

# 匿名函数可以在类中使用
# class A(object):
#     v = lambda self, x: x + 2
#
#     # def v(self, x):
#     #     return x + 1
# obj = A()
# print(obj.v(2))

# 约束
# BaseMessage类用于约束,约束其派生类:保证派生类中必须编写send方法,不然执行可能就会报错。
# class BaseMessage(object):
#     def send(self, text):
#         raise NotImplementedError('.send() 必须被重写')
#
# class Email(BaseMessage):
#     # def send(self, text):
#     #     print('发送邮件')
#     pass
#
# obj = Email()
# obj.send(1)

# 抽象类 约束,约束继承它的派生类必须实现它其中的抽象方法。
# 如果说类是从一堆对象中抽取相同的内容而来的,那么抽象类就是从一堆类中抽取相同的内容而来的,内容包括数据属性和函数属性。
# from abc import ABCMeta, abstractmethod
# class Base(metaclass=ABCMeta): # 定义抽象类
#     def f1(self):
#         print('test')
#
#     @abstractmethod # 定义抽象方法,无需实现功能
#     def f2(self):
#         pass
#
# class Foo(Base):
#     def f2(self):
#         print('ceshi')
#
# obj = Foo()
# obj.f2()

# 1.多继承问题
# 在继承抽象类的过程中,我们应该尽量避免多继承;
# 而在继承接口的时候,我们反而鼓励你来多继承接口
# 2.方法的实现
# 在抽象类中,我们可以对一些抽象方法做出基础实现;
# 而在接口类中,任何方法都只是一种规范,具体的功能需要子类实现

# 总结
# 1.接口及作用?
# java、c#中使用
# 2.python中使用抽象类+抽象方法实现接口类似约束

# 抽象类+抽象方法
# 人为抛出异常
# raise NotImplementedError(".send() 必须被重写.")

# 异常处理
# import os
#
# class ExistsError(Exception):
#     pass
#
# class KeyInvalidError(Exception):
#     pass
#
# def new_func(path, prev):
#     """
#     去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。
#         1000,成功
#         1001,文件不存在
#         1002,关键字为空
#         1003,未知错误
#         ...
#     :return:
#     """
#     response = {'code':1000,'data':None}
#     try:
#         if not os.path.exists(path):
#             raise ExistsError()
#
#         if not prev:
#             raise KeyInvalidError()
#         pass
#     except ExistsError as e:
#         response['code'] = 1001
#         response['data'] = '文件不存在'
#     except KeyInvalidError as e:
#         response['code'] = 1002
#         response['data'] = '关键字为空'
#     except Exception as e:
#         response['code'] = 1003
#         response['data'] = '未知错误'
#     return response
#
#
# def func(path,prev):
#     """
#     去path路径的文件中,找到前缀为prev的一行数据,获取数据并返回给调用者。
#         1000,成功
#         1001,文件不存在
#         1002,关键字为空
#         1003,未知错误
#         ...
#     :return:
#     """
#     response = {'code':1000,'data':None}
#     try:
#         if not os.path.exists(path):
#             response['code'] = 1001
#             response['data'] = '文件不存在'
#             return response
#         if not prev:
#             response['code'] = 1002
#             response['data'] = '关键字为空'
#             return response
#         pass
#     except Exception as e:
#         response['code'] = 1003
#         response['data'] = '未知错误'
#     return response
#
# def show():
#     return 8
#
#
# def run():
#     pass
#
# ret = func(r'D:\Ropon\Seafile\Work\python\code1\day25', 'ces')
# print(ret)

# 自定义异常
# class MyException(Exception):
#     def __init__(self, code, msg):
#         self.code = code
#         self.msg = msg
# lst = [1, 2, 3]
# obj = MyException('1000', '操作异常')
# dic = {}
# try:
#     # raise MyException(1000, '操作异常')
#     num = int(input('请输入'))
#     print(lst[num])
# except KeyError as obj:
#     obj.code = '1111'
#     obj.msg = 'KeyError'
#     dic['code'] = obj.code
#     dic['msg'] = obj.msg
# except ValueError as obj:
#     obj.code = '2222'
#     obj.msg = 'ValueError'
#     dic['code'] = obj.code
#     dic['msg'] = obj.msg
# except IndexError as obj:
#     obj.code = '3333'
#     obj.msg = 'IndexError'
#     dic['code'] = obj.code
#     dic['msg'] = obj.msg
#
# print(dic)

# class MyException(Exception):
#     def __init__(self, code, msg):
#         self.code = code
#         self.msg = msg
# try:
#     raise  MyException(1003, '路径不存在')
# except MyException as obj:
#     print(obj.code, obj.msg)
# except Exception as obj:
#     print(obj, '未知错误')

 

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!