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")
while
True:
str=f.readline()
if
len(str)==0:
break
print(str)
11 异常处理
11.1 错误与异常处理
1 语法错误(Syntax Errors)
2 异常(Exceptions)
while
True:
try:
int(input("Enter
an number:"))
break
except
ValueError:
print("you
input the invalid number!")
try:
f=open("number.txt")
s=f.readline()
num=int(s.strip())
except
OSError
as
err:
print("OSError:",err)
except
ValueError:
print("can
not convert into integer")
12 面向对象编程(Objected-Oriented)及装饰器(decorator)
12.1 面向对象编程
class
Student:
def
__init__(self,name,age):
self.name=name
self.age=age
def
introduce(self):
print("I'm
",self.name)
print("I'm
"+str(self.age)+"
years old!")
def
updateAge(self,newAge):
self.age=newAge
jim=Student("liangzhuang",24)
jim.introduce()
jim.updateAge(28)
print(jim.age)
12.2 装饰器
装饰函数以接收函数名参数,并且返回函数名,调用装饰函数后得到的函数是经过"装饰"的函数,示例如下:
def
deco(func):
def
inFunc():
return
"inFunc: "+func()
return
inFunc
#
@deco
def
myfunc():
return
"myfunc
called."
myfunc=deco(myfunc)
print(myfunc())
一般为了程序简洁,可采用注解的方式装饰函数,如下:
def
deco(func):
def
inFunc():
return
"inFunc: "+func()
return
inFunc
@deco
def
myfunc():
return
"myfunc
called."
#
myfunc=deco(myfunc)
print(myfunc())
本文介绍了Python的基本输入输出操作,包括从控制台获取用户输入和向文件进行读写操作的方法。此外,还详细讲解了如何处理程序运行过程中可能出现的各种异常,以及通过面向对象编程实现代码复用和维护。
290

被折叠的 条评论
为什么被折叠?



