首页 > 编程 > Python > 正文

Python基础语法(3)——文件流、异常处理、面向对象编程以及装饰器

2019-11-06 07:39:50
字体:
来源:转载
供稿:网友
10 输入输出10.1 输入输出方式介绍     可采用input方式接收控制台的输入str1=input("Please input a string:")PRint(str1)print("{}".format(str1))10.2 IO文件流写文件# -*- coding=utf-8 -*-textContext='''/Created on 2017年2月26日@author:ZhuangLiang'''f=open("text.txt","w")f.write(textContext)f.close()读文件f=open("text.txt")whileTrue:   str=f.readline()   iflen(str)==0:       break   print(str)11 异常处理11.1 错误与异常处理     1 语法错误(Syntax Errors)     2 异常(Exceptions)whileTrue:   try:        int(input("Enter an number:"))       break   exceptValueError:       print("you input the invalid number!")try:    f=open("number.txt")    s=f.readline()    num=int(s.strip())exceptOSErroraserr:   print("OSError:",err)exceptValueError:   print("can not convert into integer")12 面向对象编程(Objected-Oriented)及装饰器(decorator)12.1 面向对象编程classStudent:   def__init__(self,name,age):       self.name=name       self.age=age   defintroduce(self):       print("I'm ",self.name)       print("I'm "+str(self.age)+" years old!")   defupdateAge(self,newAge):       self.age=newAgejim=Student("liangzhuang",24)jim.introduce()jim.updateAge(28)print(jim.age)12.2 装饰器      装饰函数以接收函数名参数,并且返回函数名,调用装饰函数后得到的函数是经过"装饰"的函数,示例如下:defdeco(func):   definFunc():       return"inFunc: "+func()   returninFunc#@decodefmyfunc():   return"myfunccalled."myfunc=deco(myfunc)print(myfunc())一般为了程序简洁,可采用注解的方式装饰函数,如下:defdeco(func):   definFunc():       return"inFunc: "+func()   returninFunc@decodefmyfunc():   return"myfunccalled."#myfunc=deco(myfunc)print(myfunc())
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表