python----异常、属性
来源:互联网 发布:微课视频剪辑软件 编辑:程序博客网 时间:2024/06/04 01:01
三.异常
1.按自己方式出错
- raise语句------引发异常
raise Exception引发一个没有任何错误的普通异常。后一个例子添加了hyperdrive overload错误信息。
- 自定义异常类
2.捕捉异常
- try/except实现
try: x=int(input('enter the first number: ')) y=int(input('enter the second number: '))#input返回值为字符,int()强制转换 print(x/y)except ZeroDivisionError: print("The second number can't be zero!")运行结果:
- 传递异常
__metaclass__=type#确定使用新式类class MuffledCalculator: muffled = False #true:开启屏蔽机制,false:关闭屏蔽机制 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if(self.muffled): print('Dividion by zero is illegal') else: raise测试1:
calculator = MuffledCalculator()
print('the value of 10/2 is %f' %calculator.calc('10/2'))
print('the value of 10/2 is %f' %calculator.calc('10/2'))
运行结果:
测试2:
calculator = MuffledCalculator()
calculator.calc('10/0')#no muffled
calculator.calc('10/0')#no muffled
运行结果:
测试3:
calculator = MuffledCalculator()
calculator.muffled=True
calculator.calc('10/0')#have muffled
calculator.muffled=True
calculator.calc('10/0')#have muffled
运行结果:
- 多个except子句
try: x=int(input('enter the first number: ')) y=int(input('enter the second number: '))#input返回值为字符,int()强制转换 print(x/y)except ZeroDivisionError: print("The second number can't be zero!")except ValueError: print("That wasn't a int number,was it ?")
测试结果:
- 一个块捕捉两个异常
try: x=int(input('enter the first number: ')) y=int(input('enter the second number: '))#input返回值为字符,int()强制转换 print(x/y)except (ZeroDivisionError,ValueError): print("hava exception")测试结果:
- 捕捉对象
try: x=int(input('enter the first number: ')) y=int(input('enter the second number: '))#input返回值为字符,int()强制转换 print(x/y)except (ZeroDivisionError,ValueError) as e: #python3.x中写法 print(e)测试结果:
- 全捕捉
try: x=int(input('enter the first number: ')) y=int(input('enter the second number: '))#input返回值为字符,int()强制转换 print(x/y)except: print("something wrong happen")测试结果:
3.else子句
while True: try: x=int(input('enter the first number: ')) y=int(input('enter the second number: '))#input返回值为字符,int()强制转换 value = x/y print('x/y is ', value) except: print("something wrong happen,please try again") else: break
测试结果:
4.finally子句
不管try子句中是否发生异常,finally子句肯定会被执行
四.魔法(or特殊)方法、属性、迭代器
1.魔法方法
- 构造方法__init__
- 重写特殊的构造方法
例如:
__metaclass__=type#确定使用新式类class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print("Aaaaaah.....") self.hungry=False else: print("No,thanks!")class SongBird(Bird): def __init__(self): self.sound = 'I am a bird....' def sing(self): print(self.sound)#测试超类Birdprint("Test class Bird:")bird = Bird()bird.eat()print("After bird eats。。。。。")bird.eat()print()print("Test class SongBird:")#测试基类SongBirdsongbird = SongBird()songbird.sing()
测试结果:
如果执行songbird.eat(),结果:
在SongBird中,构造方法被重写,但新的构造方法没有任何关于初始化hungry特性的代码。
解决办法:
- 调用超类构造方法的未绑定版本(旧版本Python,仅供了解)
SongBird类中只需要添加一行代码——Bird.__init__(self)。
class SongBird(Bird): def __init__(self): Bird.__init__(self) self.sound = 'I am a bird....' def sing(self): print(self.sound)songbird = SongBird()songbird.sing()songbird.eat()songbird.eat()
测试结果:
- 使用super函数
super函数返回一个super对象,这个对象负责进行方法解析。当对其特性进行访问时,它会查找所有超类(以及超类的超类,直到找到特性为止,或者引发AtributeError异常)
class SongBird(Bird): def __init__(self): super(SongBird,self).__init__() self.sound = 'I am a bird....' def sing(self): print(self.sound)songbird = SongBird()songbird.sing()songbird.eat()songbird.eat()
测试结果:
- 析构方法__del__,避免使用
- 魔法方法集合
2.属性
- property函数
__metaclass__=type#确定使用新式类class Rectangle: def __init__(self): self.width=0 self.height=0 def setSize(self,size): self.width,self.height=size def getSize(self): return self.width,self.height size = property(getSize,setSize) #property函数创建了一个属性,访问器函数被作为参数,属性命名为size r=Rectangle()r.width=4r.height=5print("size is ",r.size)print("after change size")r.size=150,100print("width is ", r.width)
测试结果:
- 静态方法和类成员方法
- 静态方法在创建时被装入Staticmethod类型的对象中,定义没有self参数,能够被类本身直接调用。
- 类成员方法在创建时被装入Classmethod类型的对象中,定义时需要名为cls的类似于self的参数(自动绑定到类),可以直接用类的具体对象调用
__metaclass__=type#确定使用新式类class MyClass: @staticmethod def smethod(): print("This is a static method") @classmethod def cmethod(cls): print("This is a class method of ",cls) MyClass.smethod()MyClass.cmethod()
运行结果:
3.迭代器
迭代器就是具有next方法(在调用时不需要任何参数)的对象。调用next方法,迭代器会返回它的下一个值。如果next被调用,但迭代器没有值可以返回,就会引发一个stopIteration异常。__iter__方法返回一个迭代器。(python3.x使用__next__而不是next)
一个实现了__iter__方法的对象是可迭代的,一个实现了next方法的对象则是迭代器
__metaclass__=type#确定使用新式类class Fibs: def __init__(self): self.a=0 self.b=1 def __next__(self): self.a,self.b=self.b,self.a+self.b return self.a def __iter__(self): return self fibs=Fibs()for f in fibs: if(f>1000): print(f) break else: print("when f < 1000 ,the value of f is ",f)
运行结果:
4.生成器
未完!
0 0
- python----异常、属性
- python AttributeError属性异常
- python-多态、类属性、类方法、静态方法、异常
- Python 异常
- python 异常
- python 异常
- python异常
- 【Python】异常
- python异常
- python异常
- python异常
- PYTHON-异常
- python异常
- Python 异常
- Python异常
- Python异常
- Python异常
- Python异常
- 从零开始学习cpld(1)
- 单例模式以及单例模式与静态类的对比
- 三门问题
- 算法导论学习之归并排序
- OSX: Garageband/LogicPro各种安装包下载
- python----异常、属性
- 基础加强-IntroSpector(内省)
- PHP自学过程之 运算符与流程控制
- 表单练习题
- 64位系统深入剖析:不仅是内存这么简单
- PC110305/UVA10188
- 第五周项目1.4在构造函数中使用参数初始化表对数据成员初始化
- 稀疏矩阵用三元数组表示后的矩阵乘法算法 集合!
- JavaScript 类型转换