Python练习-文件读写
本部门练习Python文件读写操作。与Java类似,需要注意文件打开后的关闭操作。 # 文件操作 import os # 因为一定要关闭文件流,所以写在finally里 try: file = open('.\\resources\\file_demo') print(file.read()) finally: if file: file.clos...
本部门练习Python文件读写操作。与Java类似,需要注意文件打开后的关闭操作。 # 文件操作 import os # 因为一定要关闭文件流,所以写在finally里 try: file = open('.\\resources\\file_demo') print(file.read()) finally: if file: file.clos...
本部分学习Python代码调试和测试方法。可用的代码调试方法有: print打印 logging记录 pdb调试/pdb.settrace() unittest单元测试等。 样例代码如下: # 程序调试 # 1.用断言 import pdb def div(s): n = int(s) assert n != 0, "n is zero" return 10 ...
本部分练习python中的异常处理,相当于Java中的try…catch…finally,不同的是: 1.Python中的语句是try….except….finally 2.Python中有try….except…else…finally语句,期中else语句是当没有异常捕获时执行; 3.Python中主动抛出异常的语句时raise。 # 1.try except 捕获error imp...
本部分学习用Type和metaClass动态创建类,添加属性和方法。 # 使用元类 type 可以检查对象类型,也可以动态创建一个新类 class Student(object): def __init__(self, name, gender): self.name = name self.gender = gender def do_s...
本部分学习Python中定制类和枚举部分。定制类其实就是类似Java中复写String,HashCode等方法,不过更灵活,可覆盖的方法更多。 # 1. 定制类 class Student(): def __init__(self, name, age): self.__name = name self.__age = age @prope...
本部分练习Python高级面向对象内容,主要学习__slots__和@property相关用法,详见代码: # 1. 使用__slots__,限制允许动态绑定到实例上的属性或方法 from types import MethodType class Student(): # 使用__slot__ 限制绑定属性,只允许绑定如下属性或者方法。 __slots__ = ("a...
本部分练习Python面像对象编程基础知识。练习代码如下: python面像对象学习相关代码 import types from demo.module.module import Student import demo.module.module as im_module # 对象类型 print(type(123)) print(type("123")) print(type(S...
本部分练习Python模块和初级面像对象相关知识。练习代码如下: #!/usr/bin/env python3 # -*- coding: utf-8 -*- ' a test module ' __author__ = 'OneCoder Lihz' import sys def test(): args = sys.argv print("args:", arg...
本部门练习Python函数式编程,第二部分。 # 1. 返回函数、闭包 import functools import time def cal_sums(*args): def do_sum(): result = 0 for x in args: result += x return result ...
本部分练习Python函数式编程。练习高阶函数、map、reduce等常用函数。 # 1. 高阶函数 from functools import reduce f = abs print(f) print(f(-10)) def absadd(x, y, f): return f(x) + f(y) print(absadd(-3, -4, f)) # 2. map...