2018-03-24

Python第四周

  • 多重继承
    1.子类继承父类(第一个为首要的继承对象,因此下面写继承父类需要按顺序写)
    2.子类在继承父类的方法时要这样写(Father.init(self, name))
class Son(Father, Monk, Muscial):
    def __init__(self, name, nickname, art_name):
        Father.__init__(self, name)
        Monk.__init__(self, nickname)
        Muscial.__init__(self, art_name)
  • 正则表达式

1.30分钟入门教程匹配规则
2.正则表达式中match(从头开始匹配), search(搜寻), sub(替换),split(撕碎), findall(查找整个内容)用法。
a.用法如下

import re


def main():
    # [email protected]
    # ^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
    # ((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)
    # 1[38]\d{9}|14[57]\d{8}|15[0-35-9]\d{8}|17[678]\d{8}
    pattern = re.compile(r'(?<=\D)1[345789]\d{9}(?=\D)') #compile创建一个模型按照此模板查找对象
    sentence = '重要的事情说8130000000000遍我的手机号是13512346789不是13300998765,不是110'
    mylist = re.findall(pattern, sentence) #从头到尾查询满足条件的,传入两个参数,第一个为模型,第二个为提供的字符串
    mylist = pattern.findall(sentence) # 也可以这样写
    #如果导入模块的时候写的是from re import findall, 后面在用findall时直接可以写mylist = findall(r'\d+', content)
    print(mylist)
    # iter - iterator - 迭代器
    for temp in pattern.finditer(sentence):
        print(temp)
        print(temp.group())
        print(temp.span())
    m = pattern.search(sentence)  #从头到尾搜寻,只要找到满足的条件的直接返回,接下来就不再去搜寻(直接跟模型发一个消息)
    n = pattern.match(sentence) #从头开始匹配,如果不满足直接返None
    print(n)
    while m:
        print(m.group())
        m = pattern.search(sentence, m.end())


if __name__ == '__main__':
    main()

import re


def main():
    sentence = '你个大爷你个萨比'
    #用&替换掉前面出现的字符,前面是正则的分支结构
    pure = re.sub('你|大爷|萨比', '&', sentence, flags=re.I)
    print(pure)
    sentence = 'you go your way!, i will go mine!a'
    mylist = re.split(r'[\s,!]', sentence) #按照规则撕掉规则里面的对象
    print(mylist)


if __name__ == '__main__':
    main()
from re import findall, sub, search


def foo(mo):
    val = int(mo.group('foo1'))
    return str(val ** 2)


def main():
    content = 'abc1245hello46goodbye67shit'
    mylist = findall(r'\d+', content)
    print(mylist)
    mylist1 = list(map(int, mylist))
    print(mylist1)
    #print(sum(mylist) / len(mylist))

    print(sub(r'(?P\d+)(?P[hg])', foo, content))


if __name__ == '__main__':
    main()
  • 进程和线程
    1.进程,子进程,
from multiprocessing import Process

counter = 0


def output(string):
    global counter
    while counter < 10:
        print(string, end='', flush=True)
        counter += 1


def main():
    p1 = Process(target=output, args=('Ping',))
    p1.start()
    p2 = Process(target=output, args=('Pong',))
    p2.start()
    p3 = Process(target=output, args=('hong',))
    p3.start()


if __name__ == '__main__':
    main()
import subprocess


def main():

    subprocess.call('calc')
    subprocess.call('notepad')


if __name__ == '__main__':
    main()

# 无意间看到比较好的让参数变量变少的一个方法(元组)
class Ball(object):
    def __init__(self, center, color, radius, speed):
        self._center = center
        self._color = color
        self._radius = radius
        self._speed = speed
    @property
    def radius(self):
        return self._radius
    @property
    def center(self):
        return self._center

    def move(self):
        x, y = self._center[0], self._center[1]
        sx, sy = self._speed[0], self._speed[1]
        self._center = x, y = x + sx, y + sy
        if x + self._radius >= 800 or x - self._radius <= 0:
            self._speed = -sx, sy
        if y + self._radius >= 600 or y - self._radius <= 0:
            self._speed = sx, -sy
  • 线程
    1.创建线程(target为创建线程所干的任务,args为传入的参数为元组:注意元组只有一个值时后面要加一个逗号)
import random
from threading import Thread
import time
# 如果多个任务之间没有任何的联系(独立的子任务)而且希望利用CPU的多核特性
#那么我们推荐使用多进程
#Information Technology
#摩尔定律
#安迪比尔定律
#反摩尔定律
def download(filename):
    print('开始下载%s..'%filename)
    delay = random.randint(5, 15)
    time.sleep(delay)
    print('%s下载完成, 用时%d秒。'%(filename, delay))
class DownloadTask(Thread):
    def __init__(self, filename):
        super().__init__()
        self._filename = filename
    #钩子函数/回调函数(创建了线程在执行的时候会自动的调这个方法)
    def run(self):
        download(self._filename)
def main():
    start = time.time()
    t1 = DownloadTask('Python入门')
    t1.start()
    t2 = DownloadTask('美女')
    t2.start()
    t3 = DownloadTask('nv')
    t3.start()
    #等待线程执行完成,三个任务是同时开始的,谁的时间少,谁先打印,总的时间 = 主线程 + 线程里面用时最多的那个
    # t1.join()
    # t2.join()
    # t3.join()
    end = time.time()
    print('总共耗费了%f秒'%(end - start))




if __name__ == '__main__':
    main()

2.多个线程同时访问同一个资源时,有可能因为竞争的原因导致状态出错,我们把这个资源叫做临界资源,为了保证整个程序不出错,我们需要加上一个锁(lock.acquire 和 lock.release)

import time
from threading import Thread, Lock

class Account(object):
    def __init__(self, balance):
        self._balance = 0

        self._lock = Lock()

    @property
    def balance(self):
        return self._balance
    #多个线程访问一个资源的时候就有可能因为竞争资源导致状态出错
    # 被多个线程访问的资源我们通常称为临界资源,要加保护
    def deposit(self, money):
        if money > 0:
            self._lock.acquire()
            try:
                new_balance = self._balance + money
                time.sleep(0.01)
                self._balance = new_balance
            finally:
                self._lock.release()
class AddMoneyThread(Thread):
    def __init__(self, account):
        super().__init__()
        self._account = account
#创建线程后直接调用run方法(run方法是继承并对它重写父辈线程的方法)
    def run(self):
        self._account.deposit(1)
def main():
    account = Account(100)
    tlist = []
    for _ in range(100):
        t = AddMoneyThread(account)
        tlist.append(t)
    #for t in tlist:
        t.start()
    for t in tlist:
        t.join()
    print('账户余额:%d园'%account.balance)
if __name__ == '__main__':
    main()


from threading import Thread

# 创建线程的两种方式(线程之间是同时进行的,无法判断每次的结果)
# 1. 直接创建Thread对象并通过target参数指定线程启动后要执行的任务
# 2. 继承Thread自定义线程 通过重写run方法指定线程启动后执行的任务


class PrintThread(Thread):

    def __init__(self, string, count):
        super().__init__()
        self._string = string
        self._count = count

    def run(self):
        for _ in range(self._count):
            print(self._string, end='', flush=True)


def main():
    # 守护线程 - 不值得保留的线程 - 其他线程如果都执行完毕了那么守护线程自动结束
    # daemon=True - 将线程设置为守护线程
    PrintThread('Ping', 10000).start()
    PrintThread('Pong', 20000).start()


if __name__ == '__main__':
    main()
  • 基于TCP,UDP的套接字
    1.创建一个服务器
from socket import socket


def main():
    # 创建一个基于tcp的套接字对象
    # 因为我们做的是应用级的产品或服务所以可以利用现有的传输服务来实现数据传输
    server = socket()
    # 绑定IP地址(网络上主机的身份标志)和端口(用来区分不同服务的IP地址的扩展)
    server.bind(('127.0.0.1', 9584))
    # 监听客户512是最适合的值,太多客户端还要排队等待监听
    server.listen(512)
    print('服务器正在启动监听。。')
    while True:
        # 通过accept方法接受客户端的连接
        # accept方法是一个阻塞式的方法 如果没有客户端
        # 连上来,那么accept方法会让代码阻塞  直到有客户端
        # 端连接成功才返回
        # accept方法返回一个元组,元组中的第一个值是代表客户端的对象
        # 元组中的第二个值又是一个元组  其中客户端的
        # 的IP地址和客户端的端口

        client, addr = server.accept()
        print(addr, '连接成功')
        print(client)
        client.send('hello'.encode('utf-8'))
        client.close()


if __name__ == '__main__':
    main()

务器正在启动监听。。
('127.0.0.1', 49366) 连接成功

from socket import socket


def main():
    client = socket()
    client.connect(('127.0.0.1', 9584))
    data = client.recv(512)
    print(type(data))
    print(data.decode('utf-8'))


if __name__ == '__main__':
    main()
#服务器
from socket import socket
from threading import Thread


def main():

    class ClientHandler(Thread):

        def __init__(self, client):
            super().__init__()
            self._client = client

        def run(self):
            try:
                while True:
                    try:
                        data = self._client.recv(1024)
                        if data.decode('utf-8') == 'byebye':
                            clients.remove(self._client)
                            self._client.close()
                            break
                        else:
                            for client in clients:
                                client.send(data)
                    except Exception as e:
                        print(e)
                        clients.remove(self._client)
                        break
            except Exception as e:
                print(e)

    server = socket()
    server.bind(('127.0.0.1', 12345))
    server.listen(512)
    clients = []
    while True:
        curr_client, addr = server.accept()
        print(addr[0], '连接到服务器.')
        clients.append(curr_client)
        ClientHandler(curr_client).start()


if __name__ == '__main__':
    main()
#客户端
from socket import socket
from threading import Thread


def main():

    class RefreshScreenThread(Thread):

        def __init__(self, client):
            super().__init__()
            self._client = client

        def run(self):
            while running:
                data = self._client.recv(1024)
                print(data.decode('utf-8'))

    nickname = input('请输入你的昵称: ')
    myclient = socket()
    myclient.connect(('127.0.0.1', 12345))
    running = True
    RefreshScreenThread(myclient).start()
    while running:
        content = input('请发言: ')
        if content == 'byebye':
            myclient.send(content.encode('utf-8'))
            running = False
        else:
            msg = nickname + ': ' + content
            myclient.send(msg.encode('utf-8'))


if __name__ == '__main__':
    main()
  • 发短信,邮件SMTP
发送短信

import urllib.parse
import http.client
import json

host = "106.ihuyi.com"
sms_send_uri = "/webservice/sms.php?method=Submit"

params = urllib.parse.urlencode({
    'account': '',
    'password': '',
    'content': '您的验证码是:147258。请不要把验证码泄露给其他人。',
    'mobile': '18251599458',
    'format': 'json'
})
print(params)
headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}
conn = http.client.HTTPConnection(host, port=80, timeout=10)
conn.request('POST', sms_send_uri, params, headers)
response = conn.getresponse()
response_str = response.read()
jsonstr = response_str.decode('utf-8')
print(json.loads(jsonstr))
conn.close()
#发邮件

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP

def main():
sender = SMTP('smtp.qq.com')
sender.login('[email protected]', 'zkezcbda')
message = MIMEMultipart()
# message['From'] = '呵呵'
# message['To'] = '瓜西西'
# message['Cc'] = '[email protected]'
message['Subject'] = '请查收附件中的数据'
text_msg = MIMEText('附件中有本月关键数据请查收!', 'plain', 'utf-8')
message.attach(text_msg)

att2 = MIMEText(open('hello.xlsx', 'rb').read(), 'base64', 'utf-8')
att2['Content-Type'] = 'application/vnd.ms-excel'
att2['Content-Disposition'] = 'attachment; filename=foo.xlsx'
message.attach(att2)

sender.sendmail('[email protected]',
                ['[email protected] '],
                message.as_string())

print('发送完成!')

if name == 'main':
main()



















你可能感兴趣的:(2018-03-24)