python 是一种多范式编程语言,支持面向对象编程 (oop)。oop 使用类和对象来组织代码,提高代码的可重用性、可扩展性和可维护性。
类 (Class)
类是对象的蓝图或模板,它定义了对象的属性(状态)和方法(行为)。例如,“自行车”就是一个类,它具有品牌、颜色、速度等属性,以及启动、加速、停止等方法。
对象 (Object)
对象是类的实例,是实际存在的实体。例如,“Activa”和“Pulsar”都是“自行车”类的对象。每个对象都有自己独特的状态。
立即学习“Python免费学习笔记(深入)”;
注意:必须先定义类才能创建对象。
为什么在Python中使用OOP?
主要原因在于其提高了代码的可重用性、可扩展性和可维护性。
示例:图片显示
from PIL import Image photo = Image.open("abcd.jpeg") photo.show()
CSV文件与Matplotlib数据可视化
CSV (Comma Separated Values) 文件是一种纯文本格式,用逗号分隔值。Matplotlib 是一个流行的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()
文件操作
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()
f = open("abcd.txt", "w") f.write("friday\nsaturday\n") # 使用 \n 换行 f.close()
f = open("abcd.txt", "a") f.write("sunday\nmonday\n") f.close()
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()
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}")
import os file_name = input("Enter file name: ") if os.path.isfile(file_name): print("File is present") else: print("File is not present")
记住在操作完成后始终关闭文件 (f.close()),释放系统资源并避免潜在错误。 可以使用 with open(...) as f: 语句,它会在代码块执行完毕后自动关闭文件,即使发生异常。
以上就是Python Day-Objectionpiended编程(OOPS),CSV,Matplotlib的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号