面向对象¶
从这里开始有“类”和“对象”,以及文件操作和测试相关。
class
:
#!/usr/bin/env python
# 创建类
class CuteCat:
def __init__(self, cat_name, cat_age, cat_color):
self.name = cat_name
self.age = cat_age
self.color = cat_color
self.isking = False
def miao(self):
print("miao!" * self.age)
cat_1 = CuteCat("Jojo", 2, "yellow")
print(f"cat's name is: {cat_1.name}")
print(f"cat's age is: {cat_1.age}")
print(f"cat's color is: {cat_1.color}")
cat_1.miao()
# 类的继承,继承了 __init__ 方法
class CuteLion(CuteCat):
def __init__(self, lion_name, lion_age, lion_color):
super().__init__(lion_name, lion_age, lion_color)
self.isking = True
def ao(self):
print("ao!" * self.age)
def miao(self):
print("I am king. I would not miao!")
lion_1 = CuteLion("Dio", 5, "gold")
print(f"lion's name is: {lion_1.name}")
print(f"lion's age is: {lion_1.age}")
print(f"lion's color is: {lion_1.color}")
# 猫!哈哈!
lion_1.ao()
lion_1.miao()
file
:
#!/usr/bin/env python
# r = read, w = write, a = append.
# a 和 w 模式下,文件不存在会创建文件,前者为追加,后者为覆写
with open("./12_file.txt", "w", encoding = "utf-8") as f:
f.write("This is line 1.\n")
f.write("This is line 2.\n")
f.write("THIS IS LINE 3.\n")
f.write("This is line 4.\n")
f.write("This is line 5.\n")
f.write("This is line 6.\n")
f.write("This is line 7.\n")
f.write("This is line 8.\n")
f.write("This is line 9.\n")
r = open("./12_file.txt", "r", encoding = "utf-8")
# readline 按行读,读到结尾返回空字符串
# readlines 读取全部内容,以行为组,返回一个字符串列表
print("以下是 readline 和 readlines :")
print(r.readline())
print(r.readline())
print(r.readlines())
r.close
r = open("./12_file.txt", "r", encoding = "utf-8")
# read 有指针,会记录读到了哪里
print("以下是 read")
content = r.read(2)
content_r = r.read()
print(content)
print(content_r)
r.close()
with open("./12_file.txt", "w", encoding = "utf-8") as f:
f.write("This is line 1.\n")
f.write("This is line 2.\n")
f.write("This is line 3.")
try_except
:
test
:
#!/usr/bin/env python
# 也可以通过 `assert` 语句产生 AssertionError 逐条测试
# 考虑到效率,建议使用 `unittest`
import unittest
from mymodule import my_calculator
class TestMyCalculator(unittest.TestCase):
def test_positive(self):
self.assertEqual(my_calculator(1), 0)
def test_negtive(self):
self.assertEqual(my_calculator(-1), -21)