Python3中类、模块、错误与异常、文件的简易教程
类
在 Python3 中,使用 class
关键字定义类。类中包含属性和方法。属性指的是类的数据成员,方法指的是类中定义的函数。
- 定义一个类
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print('Name:',self.name, ', Age:', self.age)
person1 = Person('Lily', 25)
person1.display_info()
上述代码中,定义了一个 Person
类,包含 name
和 age
两个属性,以及 display_info
方法。创建一个 person1
的实例,赋予属性值,并调用 display_info
方法打印结果 ‘Name:Lily, Age:25’。
- 继承
继承是指在一个类中使用另一个类的属性和方法,被继承的类称为父类,继承的类称为子类。
class Student(Person):
def __init__(self, name, age, stu_no):
Person.__init__(self, name, age)
self.stu_no = stu_no
def display_info(self):
print('Name:',self.name, ', Age:', self.age, ', Student No:', self.stu_no)
stu1 = Student('Mike', 18, '10201801')
stu1.display_info()
上述代码中,定义了一个子类 Student
继承自父类 Person
,并添加一个新的属性 stu_no
。重新定义 display_info
方法,打印结果 ‘Name:Mike, Age:18, Student No:10201801’。
模块
模块是 Python3 中的一个重要的概念,可以理解为一个代码库,包含函数、类等内容,方便代码的组织和复用。
- 引入模块
import math
print(math.pi) # 打印圆周率
上述代码中,使用 import
关键字引入了 math
模块,使用 .
操作符引用模块中的属性 pi
。
- 自定义模块
可以使用 import
导入自己编写的模块。假设我们在同一目录下新建了一个 mymodule.py
文件,包含以下代码:
def hello():
print('Hello, world!')
那么在其他文件中,使用 import mymodule
,即可引入 mymodule
模块。调用 hello()
方法即可打印结果 ‘Hello, world!’。
错误与异常
在程序运行中,可能会出现各种各样的错误,Python3 中对于错误的处理方式是以异常的形式进行的。若一个错误的代码部分在程序中引发了异常,程序将会停止运行。我们可以通过捕捉异常并做出响应的方式来处理这些错误情况。
- 简单的异常处理
try:
x = 5 / 0
except ZeroDivisionError:
print('被除数不能为0')
上述代码中,使用 try
和 except
关键字来捕捉 ZeroDivisionError
类型的异常,并输出 ‘被除数不能为0’。
- 抛出异常
我们也可以自己通过 raise
关键字来触发异常,该关键字的作用是抛出一个异常。
x=10
if x > 5:
raise Exception('x不能大于5。x的值为:{}'.format(x))
上述代码中,若 x
的值大于 5,将会抛出一个异常,打印结果 ‘Exception: x不能大于5。x的值为:10’。
文件操作
在 Python3 中,文件操作包括文件的读取和写入。
- 文件的读取
with open('test.txt', 'r') as f:
lines = f.readlines()
print(lines)
上述代码中,使用 open()
方法打开 ‘test.txt’ 文件,并以只读的方式读取文件内容。readlines()
方法用来读取每一行数据并返回一个列表。
- 文件的写入
with open('test.txt', 'w') as f:
f.write('hello, world')
上述代码中,使用 open()
方法打开 ‘test.txt’ 文件,并以写入的方式向文件中写入 ‘hello, world’ 字符串。
示例说明
- 类的示例
假设我们有一个系统需要对学生进行登记管理,包括姓名、年龄、性别、学号等信息,我们可以定义一个 Student
类。
class Student:
def __init__(self, name, age, gender, stu_no):
self.name = name
self.age = age
self.gender = gender
self.stu_no = stu_no
def display_info(self):
print('Name:',self.name, ', Age:', self.age, ', Gender:', self.gender, ', Student No:', self.stu_no)
stu1 = Student('Mike', 18, 'Male', '10201801')
stu1.display_info()
这里我们定义了一个 Student
类,包含 name
、age
、gender
和 stu_no
四个属性,以及一个 display_info
方法。创建一个 stu1
的实例并为其赋初值,调用 display_info
方法打印结果 ‘Name:Mike, Age:18, Gender:Male, Student No:10201801’。
- 文件读写示例
假设我们需要将日志文件中的数据进行分析,并将分析结果写入到另一个文件中,我们可以使用 Python3 中的文件操作实现。
with open('log.txt', 'r') as f1, open('result.txt', 'w') as f2:
lines = f1.readlines()
for line in lines:
if 'error' in line:
f2.write(line)
上述代码中,使用 with
语句同时打开两个文件,'log.txt'
以只读模式打开, 'result.txt'
以写入模式打开。使用 readlines()
方法读取文件内容并存放在列表 lines
中,使用 for
循环遍历每一行数据并判断是否包含关键字 'error'
,若包含则将该行数据写入到 'result.txt'
文件中。