# Python中类class中必须有__init__(self, ...)方法,self参数是必须的,类似于C#中的this
# 例如
class father_class():
def __init__(self, name, age): # 类似于C++/C#中的构造方法
self.name = name
self.age = age
# 在子类继承中,使用super来调用父类的__init__()方法
class child_class(father_class):
def __init__(self, name, age):
super.__init__(name, age)
# 导入其它模块文件中的类的方式如同导入函数
# from collections import OrderedDict
# 对象名=OrderedDict(),与普通字典的不同之处在于,OrderedDict记录了键值对的添加顺序
# Python类编码风格:类名采用驼峰法,各单词首字母大写,其余小写;类实例和模块名都采用小写字母,且各单词间用_分开
# 每个类后面紧跟一个文档字符串用以说明类
with open('file_name.txt') as file_object:
contents = file_object.read() # for line in file_object:
print(contents)
# with代表Python自动确定在不再需要使用文件时将其关闭,而不必使用close()
# contents末尾的空行可以用rstrip()去除
# 用with关键字时,用open打开的文件对象只在with代码块内可用。
# 若要在with代码块外使用,可用file_object.readlines()将文件内容存放在一个列表里。
# 可使用replace('old', 'new')将字符串中的一个单词替换成另一个单词
with open('file_name.txt', 'w') as file_object: # 第二个参数还可以是'a','r+'
file_object.write('hello python!')
# 不使用第二个参数指定打开模式时,默认按只读方式打开
# 使用try-except-else来处理异常
try:
pass
except:
pass
else:
pass
# 常见异常类型有ZeroDivisionError,FileNotFoundError等
# 使用json.dump()将内存中的内存存储到文件中,使用json.load()加载文件内容到内存中
# 须在文件头使用import json
# Python标准库中包含了代码测试工具unittest,用于为函数和类编写测试用例
import unittest
class test_class(unittest.TestCase):
"""用于测试的类"""
def test_fuction(self):
self.assertEqual('A', 'A')
unittest.main()
# 常用的断言方法
assertEqual(a, b)
assertNotEqual(a, b)
assertTrue(x)
assertFalse(x)
assertIn(item, list)
assertNotIn(item, list)