Python知识点总结(二)

Python知识点总结(二)

本文主要总结以下python知识点

  • FileIO文件操作
  • python操作MySQL
  • OOP面向对象
  • python套接字编程
  • python线程
  • python函数

FileIO文件操作

文件操作无非是打开文件,插入或读写,关闭文件

下面

成功

键盘输入

扫描二维码关注公众号,回复: 4630142 查看本文章

python操作MySQL

(之前已经写过如何利用IDEA创建python项目及PyMySQL-master)

数据库无非就是增删改查,聚合函数,函数,存储过程,权限,事务操作等

代码里面数据库不必要每次都连接可以优化,可以自己写一个Util工具类封装

#-*-encoding=utf-8-*-
import pymysql

print("================ Drop Table====================")
try:
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    cur = conn.cursor()
    cur.execute('drop table student')  #我的数据库里面有一个表student
    cur.close()
    conn.close()
except  Exception:
    print("发生异常")


print("================ Create Table====================")
try:
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    cur = conn.cursor()
    cur.execute('create table student(id int primary key auto_increment, name varchar (20), age int)')
    conn.commit()
    cur.close()
    conn.close()
except  Exception:
    print("发生异常")

print("================ Insert 插入 ====================")
try:
    # 开启连接
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    # 打开游标
    cur = conn.cursor();
    # 开始插入
    sql = "insert into student(name,age) values ('%s','%d')" %('tom',12);
    cur.execute(sql);
    conn.commit();
    cur.close()
    conn.close()
except Exception:
    print("发生异常")

print("================ Insert 插入100条记录,带有提交和回滚机制 ====================")
try:
    # 开启连接
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    # 打开游标
    cur = conn.cursor()
    # 关闭自动提交
    conn.autocommit(False);
    #执行sql
    i = 0 ;
    while i < 100 :
        sql = "insert into student(name,age) values('%s',%d)" % ("tom" + str(i),i % 100);
        #异常回滚测试
        # if(i == 50):
        #     sql = "insert"
        #执行sql插入
        cur.execute(sql)
        i += 1 ;
    #提交
    conn.commit()
except Exception:
    print("发生异常,进行回滚操作")
    conn.rollback()
finally:
    #关闭
    cur.close()
    conn.close()



print("================ Delete====================")
try:
    # 开启连接
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    # 打开游标
    cur = conn.cursor()
    # 关闭自动提交
    conn.autocommit(False);
    #执行sql
    sql = "delete from student where id > 50";
    cur.execute(sql)
    #提交
    conn.commit()
except Exception:
    print("发生异常,进行回滚操作")
    conn.rollback()
finally:
    #关闭
    cur.close()
    conn.close()


print("================ Update ====================")
try:
    # 开启连接
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    # 打开游标
    cur = conn.cursor()
    # 关闭自动提交
    conn.autocommit(False);
    #执行sql
    sql = "update student set age = age - 20 where age > 20";
    cur.execute(sql)
    #提交
    conn.commit()
except Exception:
    print("发生异常,进行回滚操作")
    conn.rollback()
finally:
    #关闭
    cur.close()
    conn.close()


print("================ select from ====================")
try:
    # 开启连接
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    # 打开游标
    cur = conn.cursor()
    # 关闭自动提交
    conn.autocommit(False);
    #执行sql
    sql = "select * from student";
    cur.execute(sql)
    res = cur.fetchall()
    for r in res :
        print(str(r[0]) + "," + r[1] + "," + str(r[2]));
    #提交
    conn.commit()
except Exception:
    print("发生异常,进行回滚操作")
    conn.rollback()
finally:
    #关闭
    cur.close()
    conn.close()


print("================ select count(*) from ====================")
try:
    # 开启连接
    conn = pymysql.connect(host='localhost', user='root', passwd='root', db='study', port=3306, charset='utf8')
    # 打开游标
    cur = conn.cursor()
    # 关闭自动提交
    conn.autocommit(False);
    #执行sql
    sql = "select count(*) from student where id > 10";
    cur.execute(sql)
    # res=cur.fetchall()
    res = cur.fetchone()
    print(res[0])
    #提交
    conn.commit()
except Exception:
    print("发生异常,进行回滚操作")
    conn.rollback()
finally:
    #关闭
    cur.close()
    conn.close()

边操作过程中边查看数据库 

python 多线程

线程:进程内部并发执行的代码段。

多线程里面最经典的就是火车站卖票及生产消费,涉及锁的技术,也就是同步问题

简单例子(特别要注意主线程太早结束还没来得及打印分线程信息,这里可以让程序sleep一下)

#-*-encoding=utf-8-*-
import threading
import _thread
import time

def helloword(arg1,arg2):
    print(arg1+arg2);

_thread.start_new_thread(helloword,("hello","word"))
#分线程还没打印,主线程已经结束
time.sleep(4)

火车票卖票问题

# -*- encoding utf-8 -*-
import threading
tickets = 100 ;
#声明一个锁对象
loc = threading.Lock()

#定义一个函数查看票余额,并取票
def getTicket():
    global loc ;
    #加锁
    loc.acquire()
    global tickets
    tmp = 0 ;
    if tickets > 0 :
        tmp = tickets ;
        tickets -= 1 ;
    else:
        tmp = 0 ;
    #释放锁
    loc.release()
    return tmp ;

#售票启用多线程,调用到getTicket函数
class Saler(threading.Thread):
    def run(self):
        while True:
            tick = getTicket();
            if tick != 0:
                print(self.getName() + " : " + str(tick))
            else:
                return ;

s1 = Saler()
s1.setName("s1")
s2 = Saler()
s2.setName("s2")
s3 = Saler()
s3.setName("s3")
s1.start()
s2.start()
s3.start()

输出结果 

python面向对象

(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。

类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。

数据成员:类变量或者实例变量用于处理类及其实例对象的相关的数据

法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写

继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。

对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。

继承:支持多重继承,__init__在父类中不会调用,需要子类显式调用,调用父类方法,使用父类名做前缀,还要携带self参数,查找方法线本类,在父类。

代码练习

# -*- encoding utf-8 -*-
class didi:
    num=200;
    def __init__(self):
        print("dididi null")
    def __init__(self,name,age):
        print("didiid"+name+str(age))
    def add(self,a,b):
        print(a+b)
        return a+b
    #析构函数
    def __del__(self):
        print("类被销毁了")

#haha=didi()
haha1=didi("hq",23)
haha1.add(1,2)
haha2=didi("lf",18)
print(hasattr(haha1,"num"))
#python内置函数,删除对象属性
#delattr(haha1,"num")
#print(hasattr(haha1, "num"))   会报错AttributeError: num
dict1 = didi.__dict__
for key in dict1.keys():
    print(key + ": " + str(dict1[key]))
#删除对象,调用析构函数,类似于finalize();
#haha2 = None ;
#del haha2
haha1 = None			#销毁对象

#继承
#定义类
class Dog:
    #类似于java中的静态成员,直接通过类访问。
    name = "dahuang" ;
    #私有成员
    __color = "yellow" ;
    #定义构造函数
    def  __init__(self,age):
        print("new Dog()..."+str(age))
        #相当于添加实例变量
        self.age = age ;
        #删除实例变量
        #del self.age ;
    def __del__(self):
        print("销毁对象了")
    def watch(self):
        print("watch house!!")
    def add(self,a,b):
        return a + b ;

class Cat:
    #静态方法.
    def HHH(s):
        print("hhhh") ;
    def __init__(self,name,age):
        self.name2 = name ;
        self.age2 = age ;
        print("i am a cat,my name is %s,i am %d years old"%(name,age))
    def catchMouse(self):
        self.__eatFish()
        print("抓了只老鼠!!!")
    #定义私有方法,只能在当前对象中访问
    def __eatFish(self):
        print("好吃!!")

class DogCat(Dog,Cat):
    def __init__(self,name,age1,age2):
        Dog.__init__(self,age2)
        Cat.__init__(self,name,age1)
        #自己的新方法
    def run(self):
        print(",,,,,,")
    #重写方法
    def catchMouse(self):
        print("抓了只青蛙!!")


dc=DogCat("tomas",20,23)
dc.run()
dc.catchMouse()

输出结果

 python套接字编程

一般分为TCP(server+客户端),UDP(sender+receiver),进程间通信会涉及到套接字编程,一般分为

面向连接的TCP:TCP(Transmission Control Protocol,传输控制协议)是基于连接的协议,也就是说,在正式收发数据前,必须和对方建立可靠的连接。

面向非连接UDP:(User Data Protocol,用户数据报协议)是与TCP相对应的协议。它是面向非连接的协议,它不与对方建立连接,而是直接就把数据包发送过去!发送的数据包有大小限制,所以有时候要切割,制定对应的协议。

tcp服务端

# -*- encoding=utf-8 -*-
import socket
#创建socket对象SOCK_STREAM表示tcp协议。
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#绑定地址
ss.bind(("localhost",8888))
#启动监听
ss.listen(0)
print("启动监听了!!")
buffer=1024
while True :
    #接受连接
    (sock,addr) = ss.accept()
    print("有连接了 : " + str(addr))
    while True :
        data = sock.recv(buffer)
        #对bytes(字节数组),decode解码字符串.
        i = int.from_bytes(data,byteorder='little')
        print("recved : " + str(i)) ;
    print("收到数据了: %s" % (s))

tcp客户端

# -*- encoding=utf-8 -*-
import socket ;
#创建socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#连接到server端
sock.connect(("localhost",8888))
# 构造字节数组数据b"hello world"
# sock.send(b"hello world")
index = 0 ;
while True :
    b = index.to_bytes(4,byteorder='little')
    #发送数据
    sock.send(b)
    print("sended : " + str(index))
    index += 1 ;
    import time ;
    time.sleep(1)
sock.close();

udp sender

# -*- encoding=utf-8 -*-
import socket
#创建socket对象SOCK_DGRAM表示udp协议。
sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sender.bind(("192.168.11.100",9999))
print("启动了udp发送者")
index = 0 ;
while True:
    msg = "hello" + str(index) ;
    msgBytes = msg.encode("utf-8");
    sender.sendto(msgBytes,("192.168.11.255",8888))
    print("发送了 : " + msg)
    index += 1 ;
    import time
    time.sleep(1)

udp reciver

# -*- encoding=utf-8 -*-
import socket

# 创建socket对象SOCK_DGRAM表示udp协议。
recver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recver.bind(("192.168.11.100", 8888))
print("启动了udp接受者")
while True:
    (data, addr) = recver.recvfrom(1024)
    msg = bytes.decode(data);
    print("接收了 from " + str(addr[0]) + ":" + str(addr[1]) + " : " + msg)

猜你喜欢

转载自blog.csdn.net/LuYi_WeiLin/article/details/85039261