_ _ new __()方法用于定义创建对象执行的操作
object类中的_ _ new __()方法完成对象创建过程中的内存空间申请,对象属性初始化等一系列的操作。_ _ new __()方法创建对象时自动运行
覆盖object类中的_ _ new __方法后创建对象将执行覆盖后的方法
class Man: # object
def __new__(cls, *args, **kwargs):
print("new方法被执行。。。") # 增加功能的操作
# 调用object的new方法
instance = object.__new__(Man) # 分配一个内存空间
# instance这是一个变量此处老师建议必须使用该单词
return instance # instance 中义:实例对象
def __init__(self, name, age):
print("init方法被执行。。。")
self.name = name
self.age = age
man1 = Man("小明", 18)
__new__()方法仅仅是python开放出来给用户来干预创建对象时的一个操作入口,该方法并不是真正直接完成分配内存,创建对象的操作,创建对象的操作由python底层统一管理。
老师认为new方法是python提供的一个接口,能做一些小小的干预,增加一些小的功能,但是不会真正影响或干预底层代码。
单例模式
class TheMan:
instance = None # 有了具体的值None→101
def __new__(cls, *args, **kwargs):
# 控制只开辟一次内存空间,那么就会创建出一个对象
# instance = None 只要创建对象,instance就会被初始化成None
if cls.instance == None:
cls.instance = object.__new__(TheMan)
return cls.instance
man1 = TheMan()
man2 = TheMan()
print(id(man1))
print(id(man2))
运行结果
两个地址一样
2635931425760
2635931425760
# is 和 ==的区别
# ==判断是两个值是否相同,is判断的是两个内存地址是否相同
class TheMan:
__instance = None # 信息私有化
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(TheMan)
return cls.__instance
man1 = TheMan()
man2 = TheMan()
print(id(man1))
print(id(man2))
文件基本操作
文件是计算机中数据持久化存储的表现形式
读写文件标准操作格式一:打开文件:file1 = open("文件名","读/写模式")
操作文件
关闭文件:file1.close()
文件操作完毕后必须关闭,否则将长期保持对文件的连接状态,造成内存溢出的现象发生。
GBK可显示中文
读写文件操作格式二(免关闭):打开文件:with open("文件名","读写模式") as file1:
操作文件
关闭文件:(自动关闭文件)
1.打开文件
file1 = open("demo.txt", "w") # read→r write→w
2.操作文件(读或写)
file1.write("hello world")
3.关闭文件
file1.close()
格式二:
with open("demo1.txt", "w") as file1:
file1.write("hello world")
文件读写模式
# 从一个文件中读取数据,然后写入另一个文件(复制)
file1 = open("demo3.txt", "r")
file2 = file1.read()
file1.close()
# 写操作 新建文件,保存内容
file3 = open("demo4.txt", "w")
file3.write(file2)
file3.close()
rb,wb,ab 读写单位字节
1KB = 1024b 字符 1M = 1024KB 1G = 1024M
文件读操作
# 分批次读取,方法一
file1 = open("hello.txt", "r")
while True:
read_file = file1.read(15) # 每次取15个字符由节约内存空间的作用
if len(read_file) == 0:
break
print(read_file, end="")
file1.close()
# 方法二
file1 = open("hello.txt", "r")
while True:
read_file1 = file1.readline() # 一次读取一行
if len(read_file) == 0:
break
print(read_file1, end="")
file1.close()
# 方法三 不推荐
file1 = open("hello.txt", "r")
read_file = file.readlines()
print(read_file)
file1.close()
文件写操作
由纯文本编辑得到的文件读写使用字符模式
非纯文本编辑得到的文件读写使用字节模式
推荐:
字节模式>字符模式
# 先读取
file1 = open("demo6.txt", "r")
read_file = file1.readlines()
print(read_file)
file1.close()
file2 = open("demo7.txt", "w")
file2.writelines(read_file)
file2.close()
文件的路径
# 绝对路径
file1 = open("d:/demo1.txt", "w")
file1.write("hello world")
file1.close()
文件的读写操作
文件操作——os模块
import os
# 文件改名
os.rename("demo8.txt", "demo7.txt")
# 文件删除
os.remove("demo7.txt")
# 创建文件夹(目录)
os.mkdir("文件一")
# 删除文件夹(目录)
os.rmdir("文件一")