python基础--异常,对象和迭代器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础--异常,对象和迭代器相关的知识,希望对你有一定的参考价值。
- 异常处理
- 面向对象
- 迭代器和生成器
python异常处理
- 下面代码触发了一个FileNotFoundError
>>> open("notexist.txt") Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: ‘notexist.txt‘
- 抛出异常
>>> raise FileNotFoundError
- 异常类型
- 捕获异常使用try,except,finally,else
try: open(r"c:\\Users\\kingsoft\\Desktop\\notexist.txt") except FileNotFoundError as e: print ("file not exist...") except (name1,name2): print ("io error is true...") else: print ("file exist..") finally: print ("always do...")
python面向对象
python是完全面向对象的,python中一切都是对象,包括变量,函数等。
- 定义一个对象
class MyException(): pass
- self 和init方法
class Person(): def __init__(self, name): self.name = name def sayname(self): print self.name m = Person("joe") print(m.sayname())
- 区分类和类的实例
class Person(): def __init__(self, name): self.name = name Person.name = name def sayname(self): print("myname is :" + self.name) print("myexceptionname is: " + Person.name) def changeothername(self, name): Person.name = name def __del__(self): print(self.name + "is gone") m = Person("joe") m.sayname() print("m.name : " + m.name) m.test="tt" print(m.test) j = Person("jason") j.sayname() j.changeothername(j.name) m.sayname()
- 类的继承,多态和封装概念
生成器和迭代器
- _iter_方法返回迭代器,迭代器指有next方法的对象
class Fibs(object): """docstring for Fibs""" def __init__(self, max): self.max = max self.a = 0 self.b = 1 def __next__(self): fib = self.a if fib > self.max: raise StopIteration self.a, self.b = self.b, self.a + self.b return fib #返回迭代器 def __iter__(self): return self fib = Fibs(1000) for f in fib: print(f, end= " ")
- 可迭代对象Iterable和迭代器Iterator
- 生成器,生成器通过yield语句快速生成迭代器,让函数变成一个生成器
#斐波那契数列 def getfibs(max): a = 0 b = 1 while a < max: a, b= b, a+b value = a yield value print(getfibs(1000)) for i in getfibs(1000): print(i)
- 简单理解生成器
def gen(): yield "hello" yield "how" yield "are" yield "you" for i in gen(): print(i)
以上是关于python基础--异常,对象和迭代器的主要内容,如果未能解决你的问题,请参考以下文章