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

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())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值