首页 > 编程语言 > 详细

Python-异常处理、双下方法

时间:2020-03-05 22:00:20      阅读:75      评论:0      收藏:0      [点我收藏+]

异常处理

  • 检测到异常后‘跳’过异常及异常下面的代码

什么时异常?

除去语法错误的就是异常,异常划分的很细,常用、更多

为什么要异常处理?

1.出现异常,异常下方的代码就不执行了(中断)

2.用户体验不良好

处理简单异常的方式

1.if处理一些简单的异常

2.try

# 异常分支:
   # 根据不同分支,执行不同逻辑
?
try:
?
  [1,2,3][7]
   print(111)
   dic = {"key":1}
   dic["name"]
except Exception:
   pass
# 分支 + 万能 + else + finally
try:
   num = int(input("请输入数字:"))
   lst = [1,2,3]
   # dic = {"name":"meet",1:"rimo"}
   # print(dic[num])
   print(lst[num])
?
except ValueError as e:
   print(e)
?
except KeyError as e:
   print(f"没有{e}这个键")
?
except IndexError as e:
   print(e)
?
except Exception as e:
   print(e)
?
else:
   print("都没有错,走我!")
?
finally:
   print("有错没有错,都走我!,清理工作")

断言assert

assert 条件  如果条件不成立直接报错

双下方法

闭包:在嵌套函数内,使用非本层且非全局的变量就是闭包

a = 10
def func(a):
   def foo():
       print(a)
   return foo()
func(1)

修改递归的最大深度

import sys
sys.setrecursionlimit(10)
def func():
   print(1)
   func()
func()

上下方法:一般是给源码程序员使用的

__len__
?
class A(object):
   def __init__(self):
       print(‘wo‘)
   def __len__(self):  # len()触发
       print(‘here‘)
       return 12  # 必须具有返回值并且返回值是整形
a = A()
len(a)
print(len(a))
?
class   A(object):
   def __init__(self,name):
       self.name = name
       print("wo")
   def __len__(self):   # len()触发
       return len(self.name)    # 必须具有返回值并且返回值是整型
a = A("alex")
print(len(a))
# wo
# 4
__hash__ 
# 一个算法,经过这个算法对一个对象进行计算会得出一个(在本次执行中的)唯一值
# 这个唯一值是一个数值,标识这个对象所在的内存位置
?
class A(object):
   def __init__(self):
       pass
a = A()
print(hash(a))  # object中具有__hash__方法
?
class A(object):
   def __init__(self,name):
       self.name = name
   def __hash__(self): # hash()触发
?
       return hash(self.name)
?
a = A("alex")
print(hash(a))
__str__  ***给用户用的
class A(object):
   def __init__(self,name,age,sex):
       self.name = name
       self.age = age
       self.sex = sex
   def __str__(self):
       print(‘here‘)
       # 必须具有返回值,返回值必须是字符串
       return f"姓名:{self.name} 年龄:{self.age} 性别:{self.sex}"
a = A(‘caijie‘,20,‘woman‘)
print(a)
b = str(a)   # print和str()都可以触发__str__
print(b)
__repr__
?
class A(object):
   def __init__(sellf):
       pass
   def __repr__(self):
       print(111)
       return ‘caijie‘
   def __str__(self):
       print(222)
       return ‘beauty‘  # str优先级高于repr 两个都存在只执行str
a = A()
print(a)
print(‘%r‘%(a))
__call__
?
class A:
   def __init__(self):
       pass
   def __call__(self, *args, **kwargs):  # 对象()调用的是__call__方法
       print("love")
       print(*args,**kwargs)
       print(self)
a = A()
a(111)
print(a)
__new__  单例模式、工厂模式等、、、、
?
class A(object):
   def __init__(self,name):
       self.name = name
       print(111)
   def __new__(cls,*args,**kwargs):
       obj = object.__new__(A) # 调用的是object类中的__new__,只有object类中的__new__能够创建空间
       print(obj)
       return obj  # 本质 object == __init__() return __init__() 触发__init__方法
a = A(‘caijie‘)
# <__main__.A object at 0x0000020BF6579550>
# 1111
print(a)  # a是对象的内存地址
# <__main__.A object at 0x0000015B794B9550>
print(a.name)
# caijie
?
单例模式
class A(object):
   __instance = None
   def __init__(self,name,age,sex):
       self.name = name
       self.age = age
       self.sex = sex
   def __new__(cls,*args,**kwargs):
       print(cls)
       if cls.__instance is None:
           obj = object.__new__(cls)
           cls.__instance = obj
       return cls.__instance
a = A("laoda",18,"男")
a1 = A("laoer",20,"男")
a2 = A("laosan",21,"女")
print(a.age)
print(a1.age)
print(a2.age)
先执行__new__后执行__init__
单例模式:不管你创建多少次,使用的都是同一个内存空间
实例化对象时发生的事
1.创建对象,并开辟对象空间 __new__
2.自动__init__方法
__enter__
__exit__
?
class MyOpen:
   def __init__(self,file,mode=‘r‘,encoding=‘utf-8‘):
       self.file = file
       self.mode = mode
       self.encoding = encoding
   def __enter__(self):
       self.f = open(self.file,self.mode,encoding=self.encoding)
       return self.f
   def __exit__(self,exc_type,exc_val,exc_tb):
       print(exc_type,exc_val,exc_tb)  # 没错误就是None
       self.f.close()
with MyOpen(‘a.txt‘) as ff:
   for i in ff:
       print(i.strip())
print(ff.read(1111))
print(ff.read())
with open("a")as f:  # 使用了上下文        
import pickle
class MyPickle:
   def __init__(self,path,mode=‘load‘):
       self.path = path
       self.mode = ‘ab‘ if mode==‘dump‘ else ‘rb‘
?
   def __enter__(self):
       self.f = open(self.path, mode=self.mode)
       return self
?
   def dump(self,content):
       pickle.dump(content,self.f)
?
   def __exit__(self, exc_type, exc_val, exc_tb):
       self.f.close()
?
   def __iter__(self):
       while True:
           try:
               yield  pickle.load(self.f)
           except EOFError:
               break
class Course:
   def __init__(self,name,price,period):
       self.name = name
       self.price = price
       self.period = period
python = Course(‘python‘,19800,‘6 months‘)
linux = Course(‘linux‘,19800,‘6 months‘)
?
with MyPickle(‘course_file‘,"dump") as f:
   f.dump(python)
   f.dump(linux)
?
with MyPickle(‘course_file‘) as p:
   for obj in p:
       print(obj.__dict__)

 

 

 

 

 

 

 

 

 

Python-异常处理、双下方法

原文:https://www.cnblogs.com/womenzt/p/12422722.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!