Python核心编程概念详解
模块与包的使用
Python程序不仅包含基础的数据结构如字典、列表、集合及其操作,还包括函数和模块的运用。下面将重点介绍Python中模块的概念。
基础模块示例
%%writefile calc.py
value = 20
def sum_values(value_list):
total = 0
for item in range(len(value_list)):
total += value_list[item]
return total
value_list = [2,4,6,8,10]
print(sum_values(value_list))
# 执行后生成.py文件
# 运行脚本
%run calc.py
# 输出结果为30
# 使用该脚本需执行以下操作
import calc
print(calc.value)
# 输出20
calc.value = 200
calc.value # 输出200
data_list = [1,3,5,7,9,11]
calc.sum_values(data_list)
# 输出36
import calc as module
module.sum_values(data_list)
# 同样输出36
from calc import value,sum_values
value
# 输出20
sum_values(data_list)
from calc import *
import os
os.remove('calc.py') # 删除脚本文件
异常处理机制
Java中使用try-catch处理异常,在Python中有类似的机制:
import math
for idx in range(5):
num_input = input('请输入数字:')
if num_input == 'q':
break
result = math.log(float(num_input))
print(result)
# 当输入负数时会出现异常,使用try-except处理
import math
for idx in range(5):
try:
num_input = input('请输入数字:')
if num_input == 'q':
break
result = math.log(float(num_input))
print(result)
except ValueError:
print('数值错误: 输入必须大于0')
break
# 不确定具体异常类型时可使用Exception基类
for idx in range(5):
try:
num_input = input('请输入数字:')
if num_input == 'q':
break
result = math.log(float(num_input))
print(result)
except ValueError:
print('数值错误: 输入必须大于0')
break
except ZeroDivisionError:
print('除零错误')
break
except Exception:
print('未知异常!')
自定义异常类
class CustomError(ValueError):
pass
name_list = ['张三','李四','王五']
while True:
user_input = input('请输入姓名:')
if user_input not in name_list:
raise CustomError('无效输入: %s' % user_input)
# 输入列表中存在的姓名正常,否则抛出异常
finally语句块
try:
1/0
finally:
print('始终执行')
# 无论是否发生异常都会执行finally块
for idx in range(10):
try:
num_input = input('请输入数字:')
if num_input == 'q':
break
result = math.log(float(num_input))
print(result)
except ValueError:
print('数值错误: 输入必须大于0')
finally:
print('清理操作')
文件操作基础
%%writefile data.txt
welcome to python
user guide
today is rainy
# 执行后生成data.txt文件
file_obj = open('./data.txt')
content = file_obj.read()
print(content)
lines = file_obj.readlines()
print(type(lines)) # list类型
print(lines)
for line in lines:
print('当前行:', line)
file_obj.close()
文件写入操作
file_obj = open('data.txt', 'w')
file_obj.write('excellent work')
file_obj.write('\n')
file_obj.write('very good')
file_obj.close()
# 覆盖原内容
file_obj = open('data.txt', 'a')
file_obj.write('additional content')
file_obj.write('\n')
file_obj.write('more content')
file_obj.close()
# 追加到文件末尾
常见问题及解决方案
file_obj = open('data.txt', 'w')
for i in range(10):
file_obj.write(str(i) + '\n')
file_obj2 = open('data.txt', 'r')
print(file_obj.read())
# 未关闭文件导致读取失败
file_obj.close()
# 正确做法是确保文件被关闭
file_obj = open('data_file.txt', 'w')
try:
for i in range(10):
10/(i-5)
except Exception:
print('错误发生在:', i)
finally:
file_obj.close()
# 推荐使用with语句自动管理文件
with open('data_file.txt', 'w') as f:
f.write('sunny day ')
面向对象编程
class Student:
count = 50
def __init__(self, student_name, student_age):
self.name = student_name
self.age = student_age
def show_count(self):
print('总数 = ', Student.count)
def show_info(self):
print('姓名 = ', self.name)
Student.__doc__
# 查看类文档
s1 = Student('alice', 16)
s2 = Student('bob', 17)
s1.name
s2.name
s1.show_info()
s1.name = 'new_name'
del s2.name
hasattr(s1, 'name')
getattr(s1, 'name')
setattr(s1, 'name', 'modified_name')
delattr(s1, 'name')
类属性操作
print(Student.__doc__)
print(Student.__name__)
print(Student.__module__)
print(Student.__bases__)
print(Student.__dict__)
类继承机制
class Human:
population = 1000
def __init__(self):
print('调用父类构造函数')
def parent_method(self):
print('调用父类方法')
def set_attribute(self, attr):
Human.population = attr
def get_attribute(self):
print('父类属性:', Human.population)
def override_method(self):
print('父类待重写方法')
class Worker(Human):
def __init__(self):
print('调用子类构造函数')
def child_method(self):
print('调用子类方法')
def override_method(self):
print('子类已覆盖')
w = Worker()
w.parent_method()
w.set_attribute(200)
w.get_attribute()
# 输出结果
w.override_method()
# 子类已覆盖
时间处理功能
import time
print(time.time())
# 输出1970年至今的秒数
print(time.localtime(time.time()))
# 转换为年月日等详细信息
print(time.asctime(time.localtime(time.time())))
# 格式化时间显示
print(time.strftime('%Y-%m-%d', time.localtime()))
# 输出格式化日期
import calendar
print(calendar.month(2021, 10))