comments):
# 子类中调用父类方法
text_from_Father = super().final_report()
print(text_from_Father)
msg = "commants from teacher: " + comments
print(msg)
print("-" * 20 + "继承" + "-" * 20)
fangfang = SixGrade('fang', 95, 6)
fangfang.final_report("You are handsome")
print(fangfang.grade)
--------------------继承--------------------
Your final value is: A
commants from teacher: You are handsome
6
4.3 多态
class SixGrade(Student):
pass
class FiveGrade(Student):
pass
def print_level(Student):
msg = Student.final_report()
print(msg)
print_level(Student('from class', 90))
print_level(SixGrade('from subclass-1', 56))
print_level(FiveGrade('from subclass-2', 85))
Your final value is: A
Your final value is: D
Your final value is: B
5. IO文件操作和OS目录操作
OS操作
import os
# 获取当前目录的绝对路径
path = os.path.abspath('.')
# 创建一个目录
os.path.join('/Users/michael', 'testdir')
os.mkdir('/Users/michael/testdir')
# 删除一个目录
os.rmdir('/Users/michael/testdir')
# 拆分路径
os.path.split('/Users/michael/testdir/file.txt') # ('/Users/michael/testdir', 'file.txt')
os.path.splitext('/path/to/file.txt') # ('/path/to/file', '.txt')
# 重命名
os.rename('test.txt', 'test.py')
# 删除文件
os.remove('test.py')
# 列出所有python文件
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
IO文件
read() |
读取全部内容 |
一般 |
readline() |
每次读出一行内容 |
占用内存最少 |
readlines() |
读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素 |
最好(内存足) |
write() |
写文件 |
|
# 读
# 下面是read()方法的使用,“r”表示read
with open('testRead.txt', 'r', encoding='UTF-8') as f1:
results = f1.read() # 读取数据
print(results)
# 下面是readline()方法的使用,“r”表示read
with open('testRead.txt', 'r', encoding='UTF-8') as f2:
line = f2.readline() # 读取第一行
while line is not None and line != '':
print(line)
line = f2.readline() # 读取下一行
# 下面是readlines()方法的使用,“r”表示read
with open('testRead.txt', 'r', encoding='UTF-8') as f3:
lines = f3.readlines() # 接收数据
for line in lines: # 遍历数据
print(line)
# 写
with open('/User/test.txt', 'w') as f:
f.write('hello')
6. 正则表达式及re模块的使用
主要参考资料为:
6.2. re模块的使用
内置的 re 模块来使用正则表达式,提供了很多内置函数:
- pattern = re.compile(pattern[, flag]):
- 参数:
- pattern: 字符串形式的正则
- flag: 可选模式,表示匹配模式
- 例子:
import re
pattern = re.compile(r'\d+')
- Pattern的常用方法
import re
pattern = re.compile(r'\d+')
m0 = pattern.match('one12twothree34four')
m = pattern.match('one12twothree34four', 3, 10)
print("-" * 15 + "Match methods" + "-" * 15)
print("found strings: ", m.group(0))
print("start index of found strings: ", m.start(0))
print("end index of found strings: ", m.end(0))
print("Span length of found strigns: ", m.span(0))
s = pattern.search('one12twothree34four')
print("-" * 15 + "Search methods" + "-" * 15)
print("found strings: ", s.group(0))
print("start index of found strings: ", s.start(0))
print("end index of found strings: ", s.end(0))
print("Span length of found strigns: ", s.span(0))
f = pattern.findall('one1two2three3four4', 0, 10)
print("-" * 15 + "findall methods" + "-" * 15)
print("found strings: ", f)
f_i = pattern.finditer('one1two2three3four4', 0