Python 类练习
最近由于工作需要用到Python写脚本,因此,因此,快速学习一下Python.
如果你学过多种语言, 学习Python就很快了。
推荐菜鸟教程Python 3的教程。Link: https://www.runoob.com/python3/python3-tutorial.html
作为学习,用了1天的时间学习一个基本语法, 以下是有关Python中类的使用方式。
这里模拟了一个文件的信息写法。
python">
import os
import datetime# 定义 Access 和 Time 类
class Access:def __init__(self, can_read, can_write):self.can_read = can_readself.can_write = can_writeclass Time:def __init__(self, access_time, change_time, modify_time):self.access_time = access_timeself.change_time = change_timeself.modify_time = modify_time# 转换为年月日时间def normalTime(self):time = []access_datetime = datetime.datetime.fromtimestamp(self.access_time)self.access_date = access_datetime.strftime("%Y-%m-%d")change_datetime = datetime.datetime.fromtimestamp(self.change_time)self.change_date = change_datetime.strftime("%Y-%m-%d")modify_datetime = datetime.datetime.fromtimestamp(self.modify_time)self.modify_date = modify_datetime.strftime("%Y-%m-%d")print("atime:" + self.modify_date + " ctime:" + self.change_date + " mtime:" + self.modify_date)time.append(self.access_date)time.append(self.change_date)time.append(self.modify_date)return time# 定义 FileClass 类
class FileClass:def __init__(self, path, file_name, extension, size, access, time):self.path = pathself.file_name = file_nameself.extension = extensionself.size = sizeself.access = accessself.time = time# 实例化 Access 和 Time 类
access_obj = Access(can_read=True, can_write=False)time_obj = Time(access_time=os.path.getatime('/'),change_time=os.path.getctime('/'),modify_time=os.path.getmtime('/')
)# 实例化 FileClass
file_obj = FileClass(path="/home/user/documents",file_name="example",extension="txt",size=1024,access=access_obj,time=time_obj
)# 打印文件对象的属性以验证
print(f"文件路径: {file_obj.path}")
print(f"文件名: {file_obj.file_name}")
print(f"文件后缀名: {file_obj.extension}")
print(f"文件大小: {file_obj.size} bytes")
print(f"文件访问权限: Read: {file_obj.access.can_read}, Write: {file_obj.access.can_write}")
print(f"文件访问时间: {file_obj.time.access_time}")
print(f"文件更改时间: {file_obj.time.change_time}")
print(f"文件修改时间: {file_obj.time.modify_time}")print(file_obj.time.normalTime())
输出结果
文件路径: /home/user/documents
文件名: example
文件后缀名: txt
文件大小: 1024 bytes
文件访问权限: Read: True, Write: False
文件访问时间: 1732197543.3288176
文件更改时间: 1731068972.3327565
文件修改时间: 1732185471.0151415
atime:2024-11-21 ctime:2024-11-08 mtime:2024-11-21
[‘2024-11-21’, ‘2024-11-08’, ‘2024-11-21’]
PS D:\OtherProjects\Python>