反射
1.概念
通過字符串操作對象中的字段【類的字段和對象的字段的 == 類屬性和實例屬性】
反射就是通過字符串的方式,導入模塊,去模塊中調用指定的函數;去到對象中操作【查找、獲取、刪除、添加】成員
本質:一直基於字符串的驅動
2.使用
getattr:獲取屬性
setattr:修改屬性的值
hasattr:判斷某個屬性是否存在
delattr:刪除某個屬性
class Person(object):
country = "CH"
def __init__(self,name,age):
self.name = name
self.__age = age
def show(self):
print("show")
@classmethod
def func1(cls):
print("111")
@staticmethod
def func2():
print("222")
#1.以往的用法
p1 = Person("jack",10)
print(p1.name)
#2.反射
#問題:通過一個字符串"name"獲取jack,“age”獲取10
print("name","age")
#方式一:__dict__
print(p1.__dict__)
print(p1.__dict__["name"])
#方式二:反射
#getattr(obj,name[,default])獲取某個對象的某個字段的值,如果字段不存在,則返回default
r0 = getattr(p1,"name")
print(r0)
#r0 = getattr(p1,"score") #AttributeError: 'Person' object has no attribute 'score'
r0 = getattr(p1,"score",100)
print(r0)
#私有化屬性
# r0 = getattr(p1,"age")
# print(r0)
r0 = getattr(p1,"_Person__age")
print(r0)
#類屬性
#對象或者類名訪問類屬性
r0 = getattr(Person,"country")
print(r0)
r0 = getattr(p1,"country")
print(r0)
#成員函數
r0 = getattr(p1,"show")
print(r0)
r0()
#類函數和靜態函數
r0 = getattr(Person,"func1")
print(r0)
r0()
r0 = getattr(p1,"func1")
print(r0)
r0()
r0 = getattr(Person,"func2")
print(r0)
r0()
r0 = getattr(p1,"func2")
print(r0)
r0()
#3.setattr(obj,name,value)
p1 = Person("jack",10)
#p1.name = "zhangsan"
setattr(p1,"name","zhangsan")
print(getattr(p1,"name"))
#4.hasattr(obj,name)
print(hasattr(p1,"name"))
print(hasattr(p1,"score"))
#5.delattr(obj,name)
delattr(p1,"name")
#print(getattr(p1,"name")) #AttributeError: 'Person' object has no attribute 'name'
模塊中的反射
import reflect02.moduleA
#1.以往的方式
print(reflect02.moduleA.num)
reflect02.moduleA.show()
a = reflect02.moduleA.A(47)
#2.反射
#Python中一切皆對象,模塊也是一個對象
print(getattr(reflect02.moduleA,"num"))
s = getattr(reflect02.moduleA,"show")
s()
A = getattr(reflect02.moduleA,"A")
print(A)
r = A(36)
print(r.a)
num = 18
def show():
print("aaaaa")
class A(object):
def __init__(self,a):
self.a = a
# 練習
# news
def video():
return "視頻"
def image():
return "圖片"
def games():
return "遊戲"
def music():
return "音樂"
def movie():
return "電影"
#需求:根據用戶輸入的內容,執行對應的操作
import reflect03.news
#方式一
# data = input("請輸入你要執行的操作:")
# if data == "music":
# print(reflect03.news.music())
# elif data == "movie":
# print(reflect03.news.movie())
# elif data == "games":
# print(reflect03.news.games())
# elif data == "image":
# print(reflect03.news.image())
# elif data == "video":
# print(reflect03.news.video())
# else:
# print("還未開通此功能")
#方式二
data = input("請輸入你要執行的操作:")
result = hasattr(reflect03.news,data)
if result:
f = getattr(reflect03.news,data)
print(f())
else:
print("還未開通此功能")
#總結:反射的好處:可以簡化代碼,提高了代碼的可維護性
單元測試和文檔測試
1、單元測試
指的是對一個函數,一個類或者一個模塊來進行正確性的校驗工作
結果;
a.單元測試用過,說明所測試的單元時正常
b.單元測試未通過,說明有bug,或是條件不成立
def mysum(x,y):
return x + y
def mysub(x,y):
return x - y
from test01.mathfunc import mysum,mysub
import unittest
#1.自定義測試類,繼承自unittest.TestCase
class Test(unittest.TestCase):
#2.重寫父類中的函數
def setUp(self):
print("開始測試時自動調用")
def tearDown(self):
print("結束測試時自動調用")
#3.定義成員函數,測試指定的函數
#命名格式:test_需要被測試的函數名
def test_mysum(self):
#使用斷言:對函數的結果做一個預判【代入法】
#參數:調用原函數的結果 預判的結果 如果預測失敗的提示信息
#含義:用自己預判的結果和函數的運算結果做比對,如果相等,則說明測試通過
self.assertEqual(mysum(1,2),3,"加法有誤")
def test_mysub(self):
self.assertEqual(mysub(2,1),1,"減法有誤")
#4.開始測試
if __name__ == "__main__":
#調用main函數,會觸發Test類中所有函數的調用
unittest.main()
2、文檔測試
import doctest
def add(x,y):
"""
求兩個數的和
:param x: 第一個數字
:param y: 第二個數字
:return: 和
example:
>>> add(2,3)
5
"""
return x + y
print(add(10,43))
#開始進行文檔測試
doctest.testmod()
#注意:必須嚴格按照命令行中的格式書寫代碼
排列組合
#排列:從n個不同的元素中取出m【m <= n】個元素,按照一定的順序排成一列,
# 稱爲從n個元素中獲取m個元素的排列【Arrangement】,當.m = n時,則成爲全排列【Permutation】
"""
例如:
1 2 3 4,從中取出3個,排列的方式?
123
213
321
312
132
231
123 124 134 234
"""
import itertools
#itertools.permutations(可迭代對象,num)
result = list(itertools.permutations([1,2,3,4],1))
print(result)
print(len(result))
"""
4-4 24
4-3 24
4-2 12
4-1 4
從n個元素中取出m個元素的排列的可能性:n! / (n - m)!
"""
#組合:從n個不同的元素中,取出m個元素爲一組,叫做從n個不同元素中取出m個元素的組合
import itertools
result = list(itertools.combinations([1,2,3,4],3))
print(result)
print(len(result))
"""
4-4 1
4-3 4
4-2 6
4-1 4
從n個不同元素中取出m個元素的組合的可能性:n!/ (m! * (n -m)!)
"""
import itertools
#驗證碼
#
result = list(itertools.permutations("0123456789",6))
# #print(result)
# print(len(result))
#
# result = list(itertools.product("0123456789",repeat=6))
# #print(result)
# print(len(result))
#密碼
#result = list(itertools.permutations("0123456789qwertyuioplkjhgfdsazxcvbnm",6))
#print(result)
#print(len(result))
result = list(itertools.product("0123456789qwertyuioplkjhgfdsazxcvbnm",repeat=4))
#print(result)
print(len(result))
正則表達式
1.案例
需求:校驗一個qq號的合法性
需求:校驗一個手機號的合法性
2.概念
正則表達式:Regular Expression,Python中提供一個模塊爲re
使用單個字符串來描述、匹配、查找或者替換指定字符串的操作
正則表達式的作用:
a.可以匹配:match
b.可以搜索:search,findall
c.可以替換:sub,subn
注意:正則表達式其實只是一個字符串,該字符串具有一定的規律,使用特定的符號來匹配特定的內容
使用場景:校驗數據【qq號,手機號,身份證號,銀行卡號,用戶名和密碼,郵箱等】
爬蟲【按照指定的條件將一個網頁中的指定的數據篩選出來】