1. 程式人生 > >Python基礎筆記_Day12_Python元類、type動態建立類、Python動態建立方法、Python運算子、Python發郵件、簡訊

Python基礎筆記_Day12_Python元類、type動態建立類、Python動態建立方法、Python運算子、Python發郵件、簡訊

Day12_Python元類、type動態建立類、Python動態建立方法、Python運算子過載、Python發郵件、簡訊

12.01_Python語言基礎(類物件)(熟悉)
12.02_Python語言基礎(動態建立類)(熟練)
12.03_Python語言基礎(type建立類)(熟練)
12.04_Python語言基礎(使用type函式建立帶有屬性的類)(掌握)
12.05_Python語言基礎(type建立帶有繼承關係的類)(掌握)
12.06_Python語言基礎(type動態建立帶方法的類)(掌握)
12.07_Python語言基礎(__class__)(掌握)
12.08_Python語言基礎(python是動態語言)(掌握)
12.09_Python語言基礎(執行中給類繫結方法)(熟練)
12.10_Python語言基礎(執行過程中刪除屬性和方法)(熟練)
12.11_Python語言基礎(@property)(掌握)
12.12_Python語言基礎(運算子的過載)(瞭解)
12.13_Python語言基礎(發郵件)(熟練)
12.14_Python語言基礎(傳送簡訊)(熟練)

12.01_Python語言基礎(元類)(瞭解)

python中的類,類同樣也是一種物件,只要使用關鍵字class
python直譯器在執行的時候會建立一個物件

class Test(object):
    pass

test = Test()
print(test)#結果為類建立物件在記憶體中的地址

判斷一個物件是否在某個類中–hasattr(obj,str)

class Test(object):
    pass

test = Test()
print(test)
print(Test)

def info(o):
    print(o)
#可以將類作為引數傳遞函式
info(test)
#可以為類新增新的的屬性
print(hasattr(Test,"new_attribute"))
Test.new_attribute = "haha"
print(hasattr(Test,"new_attribute"))
print(Test.new_attribute)

#將一個類賦值給一個變數
test1 = Test
print(test1)

12.02_Python語言基礎(動態建立類)(熟練)

動態建立類

def choose_name(name):
    if name == "haha":
        class haha(object):
            pass
        return haha
    else:
        class heihei(object):
            pass
        return heihei


myClass = choose_name("haha")
print(myClass)#函式返回的haha --->  類,不是類的例項
print(myClass())#返回類建立的例項,也是物件

python中的行內函數type()

print(type(1))
print(type("1"))
print(type(choose_name("haha")))#類的型別  返回值-->type

12.03_Python語言基礎(type建立類)(熟練)

  • 動態建立類
    • 格式:
      • type(類名,由父類名稱組成的元祖(針對繼承的情況,可以為空),包含屬性的字典(名稱和值))

type建立類案例:

Test01 = type("Test01", (), {})
print(Test01)
print(Test01())	

輸出結果:
<class '__main__.Test00'>
<__main__.Test00 object at 0x000001360A04C160>

結果:顯示和我們學習的類具有一樣型別的記憶體地址

12.04_Python語言基礎(使用type函式建立帶有屬性的類)(掌握)

  • type接受一個字典來定義類的屬性
  • type(“類名”,(),{“name”:“zhangsan”})

type建立有內容的類

Test01 = type("Test01", (), {"name": "hello", "age": 18})
print(Test01)
print(Test01())
print(Test01().name)
print(Test01().age)

輸出結果:
<class '__main__.Test01'>
<__main__.Test01 object at 0x0000025B5773B860>
hello
18

12.05_Python語言基礎(type建立帶有繼承關係的類)(掌握)

Test01 = type("Test01", (), {"name": "hello", "age": 18})
print(Test01)
print(Test01())
print(Test01().name)
print(Test01().age)


Test02 = type("Test02", (Test01,), {})
print(Test02)
print(Test02())
print(Test02.__mro__)

輸出結果:
<class '__main__.Test02'>
<__main__.Test02 object at 0x000002BBD33FBA58>
(<class '__main__.Test02'>, <class '__main__.Test01'>, <class 'object'>)

注意:

type函式中有三個引數,字串是類名,元祖中是父類的名字,字典中新增屬性

新增的屬性是類屬性,不是例項屬性

新增的方法可以使普通方法,靜態方法,類方法


12.06_Python語言基礎(type動態建立帶方法的類)(掌握)

type新增例項方法

1,新增例項方法
Test01 = type("Test01", (), {"name": "hello", "age": 18})
print(Test01)
print(Test01())
print(Test01().name)
print(Test01().age)


def test(self):
    print("haha")


Test02 = type("Test02", (Test01,), {"test": test})
print(Test02)
print(Test02())
print(Test02().test)
# demo02 = Test02().
Test02().test()
print(Test02.__mro__)

type新增一個靜態方法和類方法

1,新增靜態方法
@staticmethod
def test03():
    print("hahaha--test03")
    return "test03"


Test003 = type("Test003", (Test01,), {"test03": test03})
print(Test003)
print(Test003().test03())

2,新增類方法
@classmethod
def test04(cls):
    print("hahaha--test04")
    return "test04"


Test004 = type("Test004", (Test01,), {"test04": test04})
print(Test004)
print(Test004().test04())

總結:

元類是建立類所需要的類,建立類就是為了建立類的例項物件

python中類也是物件

元類:就是用來建立這些類(物件)的類----》元類

myclass = type(name,(),{})#使用元類建立一個物件,這個物件稱之為類

myobject = myclass()#使用類建立類的例項物件

type實際上就是一個元類,是python在幕後建立所有類的元類


12.07_Python語言基礎(class)(掌握)

__class__可以檢視元素、物件所屬的類,功能和type相似

print("-" * 30)
age = 35
print(age.__class__)
name = "zhangsan"
print(name.__class__)


def test():
    pass


print(test.__class__)  # function


class demo:
    pass


print(demo.__class__)  # type

print(age.__class__.__class__)  # type
print(name.__class__.__class__)

輸出結果:
------------------------------
<class 'int'>
<class 'str'>
<class 'function'>
<class 'type'>
<class 'type'>
<class 'type'>

12.08_Python語言基礎(python是動態語言)(掌握)

動態語言的定義

  • 變數可以任意更改,不用考慮型別
  • 類可以當做引數傳遞
  • 方法,函式可以動態新增到類中
  • 屬性可以動態新增到類中
  • 。。。 。。。

執行中給物件繫結(新增屬性)

class Person(object):
    def __init__(self, name=None, age=None):
        self.name = name
        self.age = age


P = Person("小明", "22")
P.sex = "male"
print(P.sex)

輸出結果:
male

執行的過程中給類繫結屬性

class Person(object):

    def __init__(self, name=None, age=None):
        self.name = name
        self.age = age


p = Person("小麗", "23")
Person.sex = None
print(p.sex)

總結:

執行中給物件繫結屬性-----》直接通過例項物件設定

執行中給類繫結屬性-----》直接通過類物件設定


12.09_Python語言基礎(執行中給類繫結方法)(熟練)

####使用type動態新增方法

print("-" * 30)

class Person(object):
    def __init__(self, name=None, age=None):
        self.name = name
        self.age = age

    def eat(self):
        print("吃飯....")

def run(self, speed):
    print("%s在移動,速度%s" % (self.name, speed))

p = Person("老王", 23)
p.eat()

# p.run()
person = type("person", (Person,), {"run": run})
P = person("小王", "24")
P.run("220")

輸出結果:
------------------------------
吃飯....
小王在移動,速度220

使用types動態新增方法

print("*" * 30)

import types

class Person(object):
    def __init__(self, name=None, age=None):
        self.name = name
        self.age = age

    def eat(self):
        print("吃飯....")

def run(self, speed):
    print("%s在移動,速度%s" % (self.name, speed))

P = Person("小王","24")
# P.run("220")

P.run = types.MethodType(run,P)#第一個引數L:需要新增的方法,引數二:新增到該類的例項物件
P.run("100")

執行結果:
******************************
小王在移動,速度100

動態新增一個靜態方法

# 定義一個類方法
@classmethod
def testClass(cls):
    cls.num = 150


# 定義一個靜態方法
@staticmethod
def testStatic():
    print("----static method-----")
P = Person("老王",22)
Person.testClass = testClass    # 把靜態方法加入到類中
Person.testClass()              # 呼叫類的靜態方法,執行方法中的方法體
print(Person.num)               # 輸出呼叫內容

print("$" * 30)
# 新增靜態方法
Person.testStatic = testStatic
Person.testStatic()

輸出結果:
******************************
150
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
----static method-----

12.10_Python語言基礎(執行過程中刪除屬性和方法)(熟練)

  • 刪除的方法:
    • del 物件.屬性名
    • delattr(物件,“屬性名”)

12.11_Python語言基礎(@property)(掌握)

私有的屬性新增給getter和setter

class Money(object):
    def __init__(self):
        self.__money = 0

    def getMoney(self):
        return self.__money

    def setMoney(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error:不是整型")
	# 先後呼叫兩個方法,呼叫set方法的值,通過set設定
    money = property(getMoney, setMoney)  


a = Money()
print(a.money)
a.money = 100
print(a.money)

print(a.getMoney())

使用property實現getter 和 setter方法的功能

如何實現set/get------》修飾器-----》@property
@property--->屬性函式,可以對屬性賦值時候做必要的檢查,並保證程式碼的原有功能
作用:
1.將方法轉化為只讀
2.重新實現一個屬性的設定和讀取方法,可做邊界判定

class Money:
    def __init__(self):
        self.__money = 0

    @property
    def money(self):
        return self.__money

    @money.setter
    def money(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error....")


a = Money()
print(a.money)
a.money = 189
print(a.money)

案例2:

#使用set和get方法
class Person(object):
    def __init__(self,name,age):
        #屬性直接對外暴露
        # self.age = 12
        #限制屬性
        self.__name = name
        self.__age = age
    def getAge(self):
        return self.__age
    def setAge(self,age):
        if age < 0:
            age = 0
        self.__age = age

# 使用修飾器實現set和get功能
print("*" * 30)


class Person:
    def __init__(self):
        self.__name = "oo"
        self.__age = 34

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, age):
        if age > 0 and age < 100:
            self.__age = age


p = Person()
print(p.age)

12.12_Python語言基礎(運算子的過載)(瞭解)

  • 同樣的運算子執行不同資料之間的運算時,採用不同的計算方式

運算子的過載案例1:

print(1+2)
print("1"+"2")

案例2:

class Person(object):
    def __init__(self,num):
        self.num = num

    #運算子過載
    def __add__(self, other):
        return Person(self.num+other.num)
    def __str__(self):
        return "num="+str(self.num)
per1 = Person(1)
per2 = Person(2)
print(per1+per2)#3  ====print(per1.__add__(per2))
print(per1.__add__(per2))
print(per1)
print(per2)

不同的型別資料用加法會有不同的解釋


12.13_Python語言基礎(發郵件)(瞭解)

SMTP是SIMPLE MAIL TRANSFER PROTOCOL的縮寫,
一般的發信軟體,如Outlook Express、FoxMail、Eudora都是使用這個協議進行發信的。
SMTP Host 中文意思就是"簡單郵件傳送協議伺服器"
一般免費的郵箱,如下列出的,他們的SMTP伺服器就是在域名前加上smtp就行了.
smtp.163.com
smtp.21cn.com
smtp.sina.com.cn
smtp.sohu.com
smtp.126.com
對應的別一個郵件協議是:POP3(Post Office Protocol 3)。
它規定怎樣將個人計算機連線到Internet的郵件伺服器和下載電子郵件的電子協議。
它是因特網電子郵件的第一個離線協議標準,POP3允許使用者從伺服器上把郵件儲存到本地
主機(即自己的計算機)上,同時刪除儲存在郵件伺服器上的郵件,
而POP3伺服器則是遵循POP3協議的接收郵件伺服器,用來接收電子郵件的。

乞丐版

from email.mime.text import MIMEText

msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')

# 輸入Email地址和口令:
from_addr = "[email protected]"
password = "XXXXXX"
# 輸入SMTP伺服器地址:
smtp_server = "smtp.126.com"
# 輸入收件人地址:
to_addr = "[email protected]"

import smtplib

server = smtplib.SMTP(smtp_server, 25)  # SMTP協議預設埠是25
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

精裝版

12.14_Python語言基礎(傳送簡訊)(瞭解)

使用億信互聯

# 介面型別:互億無線觸發簡訊介面,支援傳送驗證碼簡訊、訂單通知簡訊等。
# 賬戶註冊:請通過該地址開通賬戶http://user.ihuyi.com/register.html
# 注意事項:
# (1)除錯期間,請使用用系統預設的簡訊內容:您的驗證碼是:【變數】。請不要把驗證碼洩露給其他人。
# (2)請使用 APIID 及 APIKEY來呼叫介面,可在會員中心獲取;
# (3)該程式碼僅供接入互億無線簡訊介面參考使用,客戶可根據實際需要自行編寫;

# !/usr/local/bin/python
# -*- coding:utf-8 -*-
import http.client
import urllib.parse

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

# 檢視使用者名稱 登入使用者中心->驗證碼通知簡訊>產品總覽->API介面資訊->APIID
account = "C45031386"
# 檢視密碼 登入使用者中心->驗證碼通知簡訊>產品總覽->API介面資訊->APIKEY
password = "481af8a3a877b0275d0adb91d0d7fdae"


def send_sms(text, mobile):
    # 引數
    params = urllib.parse.urlencode(
        {'account': account, 'password': password, 'content': text, 'mobile': mobile, 'format': 'json'})
    # 請求頭
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    # 連結目標
    conn = http.client.HTTPConnection(host, port=80, timeout=30)
    # 發起請求
    conn.request("POST", sms_send_uri, params, headers)
    # 獲取響應
    response = conn.getresponse()
    # 獲取響應內容
    response_str = response.read()
    # 關閉連線
    conn.close()
    # 把結果返回給呼叫者
    return response_str


if __name__ == '__main__':
    # 手機號碼
    mobile = "1897012800"
    # 傳送的驗證碼內容
    text = "您的驗證碼是:121254。請不要把驗證碼洩露給其他人。"

    print(send_sms(text, mobile))