python 是一种多范式编程语言,支持面向对象编程 (oop)。oop 使用类和对象来组织代码,提高代码的可重用性、可扩展性和可维护性。
类 (Class)
类是对象的蓝图或模板,它定义了对象的属性(状态)和方法(行为)。例如,“自行车”就是一个类,它具有品牌、颜色、速度等属性,以及启动、加速、停止等方法。
对象 (Object)
对象是类的实例,是实际存在的实体。例如,“Activa”和“Pulsar”都是“自行车”类的对象。每个对象都有自己独特的状态。
立即学习“Python免费学习笔记(深入)”;
注意:必须先定义类才能创建对象。
为什么在Python中使用OOP?
主要原因在于其提高了代码的可重用性、可扩展性和可维护性。
示例:图片显示
<code class="python">from PIL import Image
photo = Image.open("abcd.jpeg")
photo.show()</code>CSV文件与Matplotlib数据可视化
CSV (Comma Separated Values) 文件是一种纯文本格式,用逗号分隔值。Matplotlib 是一个流行的Python数据可视化库,可以创建静态、动画和交互式图表。
示例:销售数据图表
<code class="python">import matplotlib.pyplot as plt
import csv
years = []
sales = []
with open("sales.csv", "r") as f:
reader = csv.reader(f)
next(reader) # 跳过表头
for row in reader:
years.append(int(row[0]))
sales.append(int(row[1]))
plt.figure(figsize=(7, 5))
plt.plot(years, sales, color="r", label="Yearly Sales")
plt.xlabel('Years')
plt.ylabel("Sales")
plt.title("Last 5 Years Sales")
plt.legend() # 添加图例
plt.show()</code>
文件操作
Python 提供了多种方法来操作文件。
打开文件的模式:
'r':读取模式(默认)。打开现有文件进行读取,文件不存在则报错。'w':写入模式。创建新文件或覆盖现有文件内容进行写入。'a':追加模式。打开现有文件并在文件末尾追加内容。'x':排他创建模式。创建新文件,如果文件已存在则报错。'b':二进制模式。用于处理二进制文件(如图片、音频)。't':文本模式(默认)。用于处理文本文件。 'r+', 'w+', 'a+' 允许读写。
示例:文件操作
<code class="python">f = open("abcd.txt", "w")
print(type(f))
print(f.name)
print(f.mode)
print(f.readable())
print(f.writable())
print(f.closed)
f.close()</code><code class="python">f = open("abcd.txt", "w")
f.write("friday\nsaturday\n") # 使用 \n 换行
f.close()</code><code class="python">f = open("abcd.txt", "a")
f.write("sunday\nmonday\n")
f.close()</code><code class="python">f = open("abcd.txt", "r")
data = f.read()
print(data)
f.close()
f = open("abcd.txt", "r")
data = f.read(5) # 读取前5个字符
print(data)
f.close()
f = open("abcd.txt", "r")
line = f.readline() # 读取一行
print(line)
f.close()
f = open("abcd.txt", "r")
lines = f.readlines() # 读取所有行到列表
for line in lines:
print(line, end="")
f.close()</code><code class="python">f = open("abcd.txt", "r")
data = f.readlines()
num_lines = len(data)
num_words = 0
num_letters = 0
for line in data:
words = line.split()
num_words += len(words)
for word in words:
num_letters += len(word)
f.close()
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of letters: {num_letters}")</code><code class="python">import os
file_name = input("Enter file name: ")
if os.path.isfile(file_name):
print("File is present")
else:
print("File is not present")</code>记住在操作完成后始终关闭文件 (f.close()),释放系统资源并避免潜在错误。 可以使用 with open(...) as f: 语句,它会在代码块执行完毕后自动关闭文件,即使发生异常。
以上就是Python Day-Objectionpiended编程(OOPS),CSV,Matplotlib的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号