当前位置:首页 > 技术 > 正文内容

Python核心编程概念详解

访客 技术 2026年7月15日 1

模块与包的使用

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))

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。