第8课:异常处理、面向对象编程、发送邮件、url编码

1. 异常处理

import traceback
import pymysql
import requests


def calc(a, b):
    res = a / b
    return res


def main():

    money = input("输入多少钱:")
    month = input("还几个月:")
    try:
        res = calc(int(money), int(month))
    except ZeroDivisionError as e:  # try里面的代码如果出错了,走except里面带的代码
        traceback.print_exc()  # 只是输出错误信息,不影响代码继续执行
        print("月份必须是大于1的整数, %s" % e)
    except ValueError as e:
        print("输入必须是整数,%s" % e)
    except Exception as e:  # 捕获所有的异常
        print("未知错误,%s" % e)
    else:  # 没有出错的情况下走else中的代码
        print('每个月应还多少钱', res)
    finally:  # 不管有没有捕捉到异常,都要执行的代码
        pass
    print("hahahha")


def req():
    url = 'http://api.nnzhp.cn/api/user/all_stu'
    mpp = {'Referer': 'http://api.nnzhp.cn/'}
    res = requests.get(url, headers=mpp)
    print(res.json().get('stu_info'))
    if len(res.json().get('stu_info')) > 0:
        pass
    else:
        raise Exception('接口未返回数据')  # raise主动抛出异常,程序中断
        # raise ValueError
    print("hahha")


req()

2.  面向对象编程

 1)类

'''
定义类名时,最好大写
用类的话,得先实例化
self代表的是实例化好的对象,即本类对象
私有函数,私有变量:出了类就不能使用的了。
'''


class Car():  # 类是一个模型,模板
    # 构造函数,类初始化时执行
    # 如果类实例化时需传入一组参数,需在__init__函数中写参数
    def __init__(self, color, window):
        self.color = color
        self.window = window
        self.price = 1000
        print("init...")

    def run(self):
        print("汽车在跑。。。")

    def my_self(self):

        print("我是一个汽车,我的颜色是:%s,我有%s个窗户" % (self.color, self.window))


bus = Car("黄色", "3")  # 实例化, 把模型做成实际的汽车,这个过程叫实例化
# 实例就是具体造出来的东西,通过类实例化造出的东西,就是实例。
# 对象,即实例
bus.my_self()

 self小结

class My(object):
    country = "China"  # 类变量

    def __init__(self, name):
        self.name = name  # 实例变量,必须实例化后才能用的变量,也称为成员变量
        self.cry()

    def cry(self):
        print("%s is crying..." %self.name)

    def learn(self):
        self.skill = ["开车"]

    def my_self(self):
        print("我的名字是【%s】 我会【%s】" %(self.name, self.skill))


print(My.country)
qxy = My('qxy')
qxy.skill = "写代码"
qxy.learn()
qxy.my_self()  # 我的名字是【qxy】 我会【写代码】
print(qxy.name)

 2)继承

# 继承
#     父类有的变量 函数,子类全部能继承到
#     如果定义的类,有很多重复功能,那么可以将它定义为父类
#


class Father(object):
# 属性方法:看上去好像是一个属性,实际是一个方法,也得实例化后才能使用 @property def money(self): return 100000 def smoke(self): print("抽烟") def drink(self): print("喝碱水") def run(self): print("每天喝水") class Yjz(Father): def drive(self): print("我会开车") yjz = Yjz() print(yjz.money) class Animal(object): def eat(self): print("i am eating")

 3) 私有函数、私有变量

import redis


class MyRedis(object):
    xiaohei = "小黑"

    def __init__(self, host, password='', port=6379):
        self.__host = host  # 私有变量,只能在类里面使用,在类外面使用提示不存在这个变量
        self.password = password
        self.port = port
        # self.__conn_redis()

    def __conn_redis(self):  # 私有方法,只能在类里面使用
        print(self.__host)
        self.conn = redis.Redis(host=self.__host,password=self.password, port=self.port)

    def get(self, k):
        return self.conn.get(k).decode()

    # 静态方法:只是写在了类里面的方法,用不了self的属性或方法,调用不了类中的其它函数
    @staticmethod
    def other():
        print("我是other方法")

    # 类方法:不需要实例化就可以直接使用,可以使用类的变量和方法
    @classmethod
    def class_function(cls):
        print(cls.xiaohei)
        cls.class_function1()
        # print(cls.get(cls,'session:qxy'))

    @classmethod
    def class_function1(cls):
        print("类方法2")


r = MyRedis('127.0.0.1')
MyRedis.other()
# print(r.get('session:qxy'))
# print(r.__host)
# print(r.__conn_redis)
MyRedis.class_function()

 4) 析构函数

import pymysql


class OpMySql1:  # 经典类
    pass


class OpMySql(object):  # 新式类

    # 析构函数,实例被销毁时执行此函数
    def __del__(self):
        print("over")
        self.cur.close()
        self.conn.close()


bus = OpMySql('***', '**', '***', '***')
print(bus.db_execute("select * from user;"))
# del bus  # 这也是实例被销毁的一种写法,销毁时会调用__del__方法
# bus.close()

3. 发送邮件 

import smtplib  # 发邮件的模块
from email.mime.text import MIMEText  # 构造邮件内容的对象
from email.mime.multipart import MIMEMultipart  # 发附件要导入的模块

email_host = 'smtp.126.com'  # 邮箱地址

email_sender = '**@126.com'  # 发送者账号
email_pwd = '***'  # 发送者密码
email_receiver_list = "**@qq.com, **@qq.com"  # 收件人邮箱,多个账号的话
me = email_sender
# msg = MIMEText('邮件发送测试内容')  # 邮件内容
# msg['Subject'] = '邮件测试主题'  # 邮件主题
# msg['From'] = me  # 发送者账号
# # msg['To'] = maillist  # 接收者账号列表
# attachment 附件
attach_obj = MIMEMultipart()  # 创建带附件邮件的对象
file = 'a.txt'
content = "邮件正文"
att = MIMEText(open(file, encoding='utf-8').read())  # 邮件内容对象
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s"' % file
attach_obj.attach(att)
# msg.attach(MIMEText(content))  # 邮件正文的内容
attach_obj['Subject'] = '邮件测试主题'  # 邮件主题
attach_obj['From'] = me  # 发送者账号
attach_obj['To'] = email_receiver_list  # 接收者账号
# smtp = smtplib.SMTP_SSL(email_host,port=465)#qq邮箱
# smtp = smtplib.SMTP(email_host,port=25)#其他邮箱
# smtp.login(email_user,email_pwd)
# smtp.sendmail(email_user,maillist,msg.as_string())
# smtp.quit()

smtp = smtplib.SMTP('smtp.126.com', port=25)  # 和邮箱服务器建立连接
smtp.login(me, email_pwd)
# attach_obj['To']是str类型,sendemail()中接收邮件人是list类型
smtp.sendmail(me, email_receiver_list.split(','), attach_obj.as_string())  # 将邮件对象转换为string
# smtp = smtplib.SMTP(email_host, port=25)  # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
# smtp.login(email_user, email_pwd)  # 发送者的邮箱账号,密码
# smtp.sendmail(me, maillist, msg.as_string())
# # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
smtp.quit()  # 发送完毕后退出smtp
print('email send success.')

4. URL编码

import urllib.parse
s = "besttest 自动化测试"
print(urllib.parse.quote(s))  # url编码  
# 打印结果:besttest%20%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95
src = "https://www.baidu.com/s?ie=UTF-8&wd=%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95"
# src
print(urllib.parse.unquote(src))  # url解码  
# 打印结果: https://www.baidu.com/s?ie=UTF-8&wd=自动化测试
print(urllib.parse.unquote_plus(src))  # 加强版url解码  
# 打印结果: https://www.baidu.com/s?ie=UTF-8&wd=自动化测试

  

原文地址:https://www.cnblogs.com/qiezizi/p/8464572.html