单继承
class luban:def __init__(self, name):self.name = nameself.skill = "摸鱼飞弹"self.damageLevel = 20def attack(self):print("{} 使用了技能{} ,给敌方带来了极大的困扰\n""并有{}% 的机会造成一击必杀的效果".format(self.name, self.skill, self.damageLevel))class luban7(luban):pass# __name__ :魔法方法:类似于main函数,只在当前python文件做一个测试的入口
# 一旦运行,系统直接执行 __name__ 入口下的代码
if __name__ == '__main__': # 输入main提示补全lu = luban7("鲁班七号")lu.attack() # 访问基类继承过来的方法
多继承
class luban:def __init__(self, name):self.name = nameself.skill0 = "摸鱼飞弹"self.damageLevel = 20def attack(self):print("{} 使用了技能{} ,给敌方带来了极大的困扰\n""并有{}% 的机会造成一击必杀的效果".format(self.name, self.skill0, self.damageLevel))class spaceLab:def __init__(self, name):self.name = nameself.skill1 = "太空嘴炮"self.perDamage = 30def attack(self):print("{} 使用了技能{} ,给敌方带来了极大的困扰\n""并有{}% 的机会摧毁敌方水晶".format(self.name, self.skill1, self.perDamage))# 多继承,继承顺序 从右边开始,左边类的方法被继承会隐藏右边类的同名方法
class luban7(luban, spaceLab):# 派生类重写 __init__ 魔法方法def __init__(self, name):# 显示调用基类的 构造函数进行初始化 基类部分spaceLab.__init__(self, name)luban.__init__(self, name)self.name = nameself.skill2 = "7号嘴炮"self.damage = 50def attack(self):print("{} 使用了技能{} ,给敌方带来了极大的困扰\n""并有{}% 的机会摧毁自家水晶".format(self.name, self.skill2, self.damage))def attack0(self):luban.attack(self)def attack1(self):spaceLab.attack(self)# __name__ :魔法方法:类似于main函数,只在当前python文件做一个测试的入口
# 一旦运行,系统直接执行 __name__ 入口下的代码
if __name__ == '__main__': # 输入main提示补全lu = luban7("鲁班七号")lu.attack()lu.attack0()lu.attack1() # 访问基类继承过来的方法
@property
class Demo:def __init__(self, v):self.__value = v@property # @property说明函数时,函数名可以当成一个成员变量的使用,目的是获得属性,提示程序效率def set(self):return self.__value@set.setter # @ xxx.setter说明下面,xxx必须是前面代码行定义的函数名def set(self, v):self.__value = vif __name__ == '__main__':obj = Demo(20)# obj.set(30)# print(obj.set())print(obj.set)obj.set = 30print(obj.set) # 直接访问函数名,相当于在访问 __value
获取目录流
import ospath = "../day2"
# os.path.exists():检测某个路径是否存在
if os.path.exists(path):print("文件夹存在")
else:print("文件夹不存在")# mkdir(): 创建一个目录os.mkdir(path)
# listdir() :列举出某个路径中的所有文件名,返回文件名的列表
files = os.listdir(path) # 当前文件夹下的所有文件名
print(type(files))
print(files)
print("1212")
for file in files:if os.path.isfile(path + "/" + file):print(file, "普通文件")elif os.path.isdir(path + "/" + file):print(file, "目录文件")
文件的操作
import osif __name__ == '__main__':# file = open(file="./file.txt", mode="w+")with open(file="./file.txt", mode="a+") as fd:# seek() : 让文件指针进行偏移fd.seek(0, os.SEEK_SET)# read(n)指定从文件中读取n字节数据 read()中不写参数n时,表示默认读取所有数据# buf = fd.read(32)# print(type(buf))# print(buf)# readline(n) : 读取一行中前n个数据# readliness() : 读取文件所有行的数据,返回一个列表buf = fd.readline(5)# buf = fd.readlines()print(buf)# 关闭打开的文件fd.close()print("hello world")
---------------------------------------------------------------------try:file = open("file.txt", "w")file.write("nihaomemedaa\n")except (IOError, FileNotFoundError) as err:print("open", err)exit(-1)try:buf = "123456789\n"file.write(buf)buf1 = b"hello world\n"file.write(buf1.decode())l1 = ["nice\n"]file.write(l1[0])# writelines() : 将列表中的所有数据写入文件中,列表中的元素要求必须是字符串类型l2 = ["I'm groot ", "Spide man ", "Iron man"]file.writelines(l2)except (TypeError,) as err:print("write:", err)exit(-1)file.close()
异常
def res(x, y):if y == 0:# 手动抛出异常raise ValueError("y == 0") # 构造值错误的匿名对象return x/yif __name__ == '__main__':a = int(input("a="))b = int(input("b="))try:print("x / y =", res(a, b))except (ValueError, ) as err: # 接受和捕获异常 后面必须跟元组类型,如果异常类型只有1种,那么必须要用,占位print("除数y不能为0", err)
多线程
from time import sleep# import threading
from threading import Threaddef music(name):for i in range(5):print("I was listening music:{}".format(name))sleep(1)def study(name):for i in range(2):print("I was study:{}".format(name))sleep(5)if __name__ == '__main__':# music("Always online")# study("《杀死那只知更鸟》")# 构造一个线程,指定target指定线程执向函数,args向线程执行函数传递数据t1 = Thread(target=music, args=("Always online", ))t1.start() # 启动线程t2 = Thread(target=study, args=("《杀死那只知更鸟》", ))t2.start()t1.join() # 阻塞等待回收线程资源t2.join()
多进程
from multiprocessing import Process
from time import sleepdef music(name):for i in range(5):print("I was listening music:{}".format(name))sleep(1)def study(name):for i in range(2):print("I was study:{}".format(name))sleep(5)if __name__ == '__main__':# music("Always online")# study("《杀死那只知更鸟》")# 构造一个进程,指定target指定线程执向函数,args向进程执行函数传递数据t1 = Process(target=music, args=("Always online", ))t1.start() # 启动线程t2 = Process(target=study, args=("《杀死那只知更鸟》", ))t2.start()t1.join() # 阻塞等待回收进程资源t2.join()
互斥锁
from time import sleep# import threading
from threading import Thread, Lockdef music(name, lock):with lock: # 使用互斥锁,自动加锁,用完自动解锁for i in range(5):print("I was listening music:{}".format(name))sleep(1)def study(name, lock):with lock:for i in range(2):print("I was study:{}".format(name))sleep(5)if __name__ == '__main__':lock = Lock() # 定义互斥锁# music("Always online")# study("《杀死那只知更鸟》")# 构造一个线程,指定target指定线程执向函数,args向线程执行函数传递数据t1 = Thread(target=music, args=("Always online", lock))t1.start() # 启动线程t2 = Thread(target=study, args=("《杀死那只知更鸟》", lock))t2.start()t1.join() # 阻塞等待回收线程资源t2.join()
Python进程间通信的方法
管道
消息队列
共享内存
TCP服务器
from socket import *# 创建套接字,构造套接字类对象
sockfd = socket(AF_INET, SOCK_STREAM, 0)
# 设置端口重用
sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
# 绑定
sockfd.bind((INADDR_ANY.to_bytes(0, byteorder="little"), 6666))
# 监听
sockfd.listen(10)while True:# 阻塞等待 接受客户端连接# (connfd, addr) = sockfd.accept()connfd, cliaddr = sockfd.accept()"""创建线程,传递连接套接字,实现多线程的TCP服务器"""print(cliaddr)while True:buf = connfd.recv(32).decode()print("recv:", buf)if len(buf) == 0:breakif buf == "exit":connfd.close()sockfd.close()exit(-1)connfd.close()
TCP客户端
from socket import *
# 创建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0)
# 连接
sockfd.connect(("127.0.0.1", 6666))while True:data = input("data=").encode()sockfd.send(data)