• 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:UserskingsoftDesktop
    otexist.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)
    

      

  • 相关阅读:
    博客地址
    node学习2
    正则表达式总结
    Git命令操作
    IDEA快捷键
    hibernate多对多(权限管理)
    所有国家的下拉框英文全称
    所有国家的下拉框英文简写
    所有国家的下拉框中文
    poj-1248 Safecracker
  • 原文地址:https://www.cnblogs.com/crazymanpj/p/6849932.html
Copyright © 2020-2023  润新知