Python之面向對象

目錄

概述html

建立類和對象python

面向對象三大特性(封裝、繼承、多態)linux

  • 封裝
  • 繼承  (繼承、多繼承、super()、派生、組合、抽象類接口)
  • 多態

類的成員redis

高級用法sql

概述

  • 面向過程:根據業務邏輯從上到下寫壘代碼
  • 函數式:將某功能代碼封裝到函數中,往後便無需重複編寫,僅調用函數便可
  • 面向對象:對函數進行分類和封裝,讓開發「更快更好更強...」
while True:
    if cpu利用率 > 90%:
        #發送郵件提醒
        鏈接郵箱服務器
        發送郵件
        關閉鏈接
 
    if 硬盤使用空間 > 90%:
        #發送郵件提醒
        鏈接郵箱服務器
        發送郵件
        關閉鏈接
 
    if 內存佔用 > 80%:
        #發送郵件提醒
        鏈接郵箱服務器
        發送郵件
        關閉鏈接
面向過程 複製粘貼
def 發送郵件(內容)
    #發送郵件提醒
    鏈接郵箱服務器
    發送郵件
    關閉鏈接
 
while True:
 
    if cpu利用率 > 90%:
        發送郵件('CPU報警')
 
    if 硬盤使用空間 > 90%:
        發送郵件('硬盤報警')
 
    if 內存佔用 > 80%:
        發送郵件('內存報警') 
函數式

 

建立類和對象

# 建立類
class Foo:
     
    def Bar(self):
        print 'Bar'
 
    def Hello(self, name):
        print('i am %s' %name)
 
# 根據類Foo建立對象obj
obj = Foo()
obj.Bar()            #執行Bar方法
obj.Hello('LBJ') #執行Hello方法 

 

面向對象三大特性(封裝、繼承、多態)

封裝

封裝,對於面向對象的封裝來講,其實就是使用構造方法將內容封裝到 對象 中,而後經過對象直接或者self間接獲取被封裝的內容數據庫

class Foo:
    # 把屬性封裝到Foo類裏
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def detail(self):
        print(self.name)
        print(self.age)


obj1 = Foo('obj1', 18)
print(obj1.name)  # 直接調用obj1對象的name屬性
print(obj1.age)  # 直接調用obj1對象的age屬性
obj1.detail()  # 間接調用obj1對象的方法  Python默認會將obj1傳給self參數,即:obj1.detail(obj1)
封裝
class Teacher:
    def __init__(self,name,age):
        # self.__name=name
        # self.__age=age
        self.set_info(name,age)

    def tell_info(self):
        print('姓名:%s,年齡:%s' %(self.__name,self.__age))
    def set_info(self,name,age):
        if not isinstance(name,str):
            raise TypeError('姓名必須是字符串類型')
        if not isinstance(age,int):
            raise TypeError('年齡必須是整型')
        self.__name=name
        self.__age=age


t=Teacher('t1',18)
t.tell_info()

t.set_info('t1',19)
t.tell_info()
封裝(對封裝的數據提供額外的操做,如數據格式限制)

 

繼承

python中類的繼承分爲:單繼承和多繼承編程

class ParentClass1: #定義父類
    pass

class ParentClass2: #定義父類
    pass

class SubClass1(ParentClass1): #單繼承,基類是ParentClass1,派生類是SubClass
    pass

class SubClass2(ParentClass1,ParentClass2): #python支持多繼承,用逗號分隔開多個繼承的類
    pass

繼承

繼承,面向對象中的繼承和現實生活中的繼承相同,即:子能夠繼承父的內容。json

class Animal:

    def eat(self):
        print("%s 吃 " % self.name)

    def drink(self):
        print("%s 喝 " % self.name)

    def shit(self):
        print("%s 拉 " % self.name)

    def pee(self):
        print("%s 撒 " % self.name)


class Cat(Animal):

    def __init__(self, name):
        self.name = name
        self.breed = ''

    def cry(self):
        print('喵喵叫')


class Dog(Animal):

    def __init__(self, name):
        self.name = name
        self.breed = ''

    def cry(self):
        print('汪汪叫')


# ######### 執行 #########

c1 = Cat('小白家的小黑貓')
c1.eat()

c2 = Cat('小黑的小白貓')
c2.drink()

d1 = Dog('胖子家的小瘦狗')
d1.eat()
繼承實例

 多繼承

一、Python的類能夠繼承多個類,Java和C#中則只能繼承一個類flask

二、Python的類若是繼承了多個類,那麼其尋找方法的方式有兩種,分別是:深度優先廣度優先數組

  • 當類是經典類時,多繼承狀況下,會按照深度優先方式查找
  • 當類是新式類時,多繼承狀況下,會按照廣度優先方式查找
1.只有在python2中才分新式類和經典類,python3中統一都是新式類
2.在python2中,沒有顯式的繼承object類的類,以及該類的子類,都是經典類
3.在python2中,顯式地聲明繼承object的類,以及該類的子類,都是新式類
3.在python3中,不管是否繼承object,都默認繼承object,即python3中全部類均爲新式類
#關於新式類與經典類的區別,咱們稍後討論
經典類 與 新式類

 

 

 

經典類多繼承
class D(object):

    def bar(self):
        print 'D.bar'


class C(D):

    def bar(self):
        print 'C.bar'


class B(D):

    def bar(self):
        print 'B.bar'


class A(B, C):

    def bar(self):
        print 'A.bar'

a = A()
# 執行bar方法時
# 首先去A類中查找,若是A類中沒有,則繼續去B類中找,若是B類中麼有,則繼續去C類中找,若是C類中麼有,則繼續去D類中找,若是仍是未找到,則報錯
# 因此,查找順序:A --> B --> C --> D
# 在上述查找bar方法的過程當中,一旦找到,則尋找過程當即中斷,便不會再繼續找了
a.bar()
新式類多繼承

經典類:首先去A類中查找,若是A類中沒有,則繼續去B類中找,若是B類中麼有,則繼續去D類中找,若是D類中麼有,則繼續去C類中找,若是仍是未找到,則報錯

新式類:首先去A類中查找,若是A類中沒有,則繼續去B類中找,若是B類中麼有,則繼續去C類中找,若是C類中麼有,則繼續去D類中找,若是仍是未找到,則報錯

注意:在上述查找過程當中,一旦找到,則尋找過程當即中斷,便不會再繼續找了

繼承過程當中子類調用父類方法,super()

class Vehicle: #定義交通工具類
     Country='China'
     def __init__(self,name,speed,load,power):
         self.name=name
         self.speed=speed
         self.load=load
         self.power=power

     def run(self):
         print('開動啦...')

class Subway(Vehicle): #地鐵
    def __init__(self,name,speed,load,power,line):
        #super(Subway,self) 就至關於實例自己 在python3中super()等同於super(Subway,self)
        super().__init__(name,speed,load,power)
        self.line=line

    def run(self):
        print('地鐵%s號線歡迎您' %self.line)
        super(Subway,self).run()

class Mobike(Vehicle):#摩拜單車
    pass

line13=Subway('中國地鐵','180m/s','1000人/箱','',13)
line13.run()
super()

派生 

固然子類也能夠添加本身新的屬性或者在本身這裏從新定義這些屬性(不會影響到父類),須要注意的是,一旦從新定義了本身的屬性且與父類重名,那麼調用新增的屬性時,就以本身爲準了。

class Foo:
    def f1(self):
        print('Foo.f1')

    def f2(self):
        print('Foo.f2')


class Bar(Foo):
    def f1(self):  # 重寫了新的方法,以本身爲準
        print('Bar.f1')


b=Bar()
b.f1()  # 調用本身的f1
b.f2()  # 調用父類的f2
子類重寫屬性/方法,以本身爲準

繼承和組合

軟件重用的重要方式除了繼承以外還有另一種方式,即:組合

組合指的是,在一個類中以另一個類的對象做爲數據屬性,稱爲類的組合

>>> class Equip: #武器裝備類
...     def fire(self):
...         print('release Fire skill')
... 
>>> class Riven: #英雄Riven的類,一個英雄須要有裝備,於是須要組合Equip類
...     camp='Noxus'
...     def __init__(self,nickname):
...         self.nickname=nickname
...         self.equip=Equip() #用Equip類產生一個裝備,賦值給實例的equip屬性
... 
>>> r1=Riven('銳雯雯')
>>> r1.equip.fire() #可使用組合的類產生的對象所持有的方法
release Fire skill

組合與繼承都是有效地利用已有類的資源的重要方式。可是兩者的概念和使用場景皆不一樣,

1.繼承的方式

經過繼承創建了派生類與基類之間的關係,它是一種'是'的關係,好比白馬是馬,人是動物。

當類之間有不少相同的功能,提取這些共同的功能作成基類,用繼承比較好,好比老師是人,學生是人

2.組合的方式

用組合的方式創建了類與組合的類之間的關係,它是一種‘有’的關係,好比教授有生日,教授教python和linux課程,教授有學生s一、s二、s3...

class People:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex

class Course:
    def __init__(self,name,period,price):
        self.name=name
        self.period=period
        self.price=price
    def tell_info(self):
        print('<%s %s %s>' %(self.name,self.period,self.price))

class Teacher(People):
    def __init__(self,name,age,sex,job_title):
        People.__init__(self,name,age,sex)
        self.job_title=job_title
        self.course=[]
        self.students=[]


class Student(People):
    def __init__(self,name,age,sex):
        People.__init__(self,name,age,sex)
        self.course=[]


egon=Teacher('egon',18,'male','沙河霸道金牌講師')
s1=Student('牛榴彈',18,'female')

python=Course('python','3mons',3000.0)
linux=Course('python','3mons',3000.0)

#爲老師egon和學生s1添加課程
egon.course.append(python)
egon.course.append(linux)
s1.course.append(python)

#爲老師egon添加學生s1
egon.students.append(s1)


#使用
for obj in egon.course:
    obj.tell_info()
例子:繼承與組合

當類之間有顯著不一樣,而且較小的類是較大的類所須要的組件時,用組合比較好

繼承之接口與抽象類

class Interface:#定義接口Interface類來模仿接口的概念,python中壓根就沒有interface關鍵字來定義一個接口。
    def read(self): #定接口函數read
        pass

    def write(self): #定義接口函數write
        pass


class Txt(Interface): #文本,具體實現read和write
    def read(self):
        print('文本數據的讀取方法')

    def write(self):
        print('文本數據的讀取方法')

class Sata(Interface): #磁盤,具體實現read和write
    def read(self):
        print('硬盤數據的讀取方法')

    def write(self):
        print('硬盤數據的讀取方法')

class Process(Interface):
    def read(self):
        print('進程數據的讀取方法')

    def write(self):
        print('進程數據的讀取方法')
接口(簡單繼承,子類徹底能夠不定義父類方法)
#_*_coding:utf-8_*_
__author__ = 'Linhaifeng'
#一切皆文件
import abc #利用abc模塊實現抽象類

class All_file(metaclass=abc.ABCMeta):
    all_type='file'
    @abc.abstractmethod #定義抽象方法,無需實現功能
    def read(self):
        '子類必須定義讀功能'
        pass

    @abc.abstractmethod #定義抽象方法,無需實現功能
    def write(self):
        '子類必須定義寫功能'
        pass

# class Txt(All_file):
#     pass
#
# t1=Txt() #報錯,子類沒有定義抽象方法

class Txt(All_file): #子類繼承抽象類,可是必須定義read和write方法
    def read(self):
        print('文本數據的讀取方法')

    def write(self):
        print('文本數據的讀取方法')

class Sata(All_file): #子類繼承抽象類,可是必須定義read和write方法
    def read(self):
        print('硬盤數據的讀取方法')

    def write(self):
        print('硬盤數據的讀取方法')

class Process(All_file): #子類繼承抽象類,可是必須定義read和write方法
    def read(self):
        print('進程數據的讀取方法')

    def write(self):
        print('進程數據的讀取方法')

wenbenwenjian=Txt()

yingpanwenjian=Sata()

jinchengwenjian=Process()

#這樣你們都是被歸一化了,也就是一切皆文件的思想
wenbenwenjian.read()
yingpanwenjian.write()
jinchengwenjian.read()

print(wenbenwenjian.all_type)
print(yingpanwenjian.all_type)
print(jinchengwenjian.all_type)
接口(抽象類繼承,子類必須從新定義父類方法)

抽象類的本質仍是類,指的是一組類的類似性,包括數據屬性(如all_type)和函數屬性(如read、write),而接口只強調函數屬性的類似性。

抽象類是一個介於類和接口直接的一個概念,同時具有類和接口的部分特性,能夠用來實現歸一化設計 

 

多態

多態指的是一類事物有多種形態。

import abc
class Animal(metaclass=abc.ABCMeta): #同一類事物:動物
    @abc.abstractmethod
    def talk(self):
        pass

class People(Animal): #動物的形態之一:人
    def talk(self):
        print('say hello')

class Dog(Animal): #動物的形態之二:狗
    def talk(self):
        print('say wangwang')

class Pig(Animal): #動物的形態之三:豬
    def talk(self):
        print('say aoao')
動物有多種形態:人,狗,豬
import abc
class File(metaclass=abc.ABCMeta): #同一類事物:文件
    @abc.abstractmethod
    def click(self):
        pass

class Text(File): #文件的形態之一:文本文件
    def click(self):
        print('open file')

class ExeFile(File): #文件的形態之二:可執行文件
    def click(self):
        print('execute file')
文件有多種形態:文本文件,可執行文件
# Python崇尚鴨子類型,即‘若是看起來像、叫聲像並且走起路來像鴨子,那麼它就是鴨子’
#兩者都像鴨子,兩者看起來都像文件,於是就能夠當文件同樣去用
class TxtFile:
    def read(self):
        pass

    def write(self):
        pass

class DiskFile:
    def read(self):
        pass
    def write(self):
        pass
鴨子模型

 

類的成員

字段(實例字段、類字段)

字段包括:普通字段和靜態字段,他們在定義和使用中有所區別,而最本質的區別是內存中保存的位置不一樣,

  • 普通字段屬於對象,在每一個對象中都要保存一份
  • 靜態字段屬於,在內存中只保存一份
  • 應用場景: 經過類建立對象時,若是每一個對象都具備相同的字段,那麼就使用靜態字段
class Province:

    # 類字段,也稱靜態字段
    country = '中國'

    def __init__(self, name):

        # 實例字段,也稱普通字段
        self.name = name


# 直接訪問實例字段
obj = Province('河北省')
print(obj.name)

# 直接訪問類字段
print(Province.country)

 

方法(普通方法、@classmethod、@staticmethod)

方法包括:普通方法、類方法和靜態方法,三種方法在內存中都歸屬於類,區別在於調用方式不一樣。

  • 普通方法:屬於綁定方法,綁定給對象;由對象調用,調用時需傳入對象做第一參數;至少一個self參數;執行普通方法時,自動將調用該方法的對象賦值給self
  • 類方法:屬於綁定方法,綁定給類;@classmethod,由調用; 至少一個cls參數;執行類方法時,自動將調用該方法的複製給cls
  • 靜態方法:屬於非綁定方法;@staticmethod,由類或對象調用;無默認參數;
class Foo:

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

    def ord_func(self):
        """ 定義普通方法,至少有一個self參數 """

        # print self.name
        print('普通方法')

    @classmethod
    def class_func(cls):
        """ 定義類方法,至少有一個cls參數 """

        print('類方法')

    @staticmethod
    def static_func():
        """ 定義靜態方法 ,無默認參數"""

        print('靜態方法')


# 調用普通方法
f = Foo("test")
f.ord_func()

# 調用類方法
Foo.class_func()

# 調用靜態方法
Foo.static_func()
普通方法、類方法、靜態方法的定義
HOST='127.0.0.1'
PORT=3306

# ===================================================================================
class MySQL:
    def __init__(self,host,port):
        self.host=host
        self.port=port

    @staticmethod
    def from_conf():
        return MySQL(HOST,PORT)

    # @classmethod #哪一個類來調用,就將哪一個類當作第一個參數傳入
    # def from_conf(cls):
    #     return cls(settings.HOST,settings.PORT)

    def __str__(self):
        return 'MySQL的__str__'

class Mariadb(MySQL):
    def __str__(self):
        return '<%s:%s>' %(self.host,self.port)


m=Mariadb.from_conf()
print(m) #咱們的意圖是想觸發Mariadb.__str__,可是結果觸發了MySQL.__str__的執行:"MySQL的__str__"


# ===================================================================================
class MySQL:
    def __init__(self,host,port):
        self.host=host
        self.port=port

    # @staticmethod
    # def from_conf():
    #     return MySQL(HOST,PORT)

    @classmethod #哪一個類來調用,就將哪一個類當作第一個參數傳入
    def from_conf(cls):
        return cls(HOST,PORT)

    def __str__(self):
        return 'MySQL的__str__'

class Mariadb(MySQL):
    def __str__(self):
        return '<%s:%s>' %(self.host,self.port)

m=Mariadb.from_conf()
print(m) # 觸發Mariadb.__str__,"<127.0.0.1:3306>"
classmethod 和 staticmethod
"""
定義MySQL類

  1.對象有id、host、port三個屬性

  2.定義工具create_id,在實例化時爲每一個對象隨機生成id,保證id惟一

  3.提供兩種實例化方式,方式一:用戶傳入host和port 方式二:從配置文件中讀取host和port進行實例化

  4.爲對象定製方法,save和get_obj_by_id,save能自動將對象序列化到文件中,文件路徑爲配置文件中DB_PATH,文件名爲id號,保存以前驗證對象是否已經存在,若存在則拋出異常,;get_obj_by_id方法用來從文件中反序列化出對象
"""
#settings.py內容
'''
HOST='127.0.0.1'
PORT=3306
DB_PATH=r'E:\CMS\aaa\db'
'''
import settings
import uuid
import pickle
import os
class MySQL:
    def __init__(self,host,port):
        self.id=self.create_id()
        self.host=host
        self.port=port

    def save(self):
        if not self.is_exists:
            raise PermissionError('對象已存在')
        file_path=r'%s%s%s' %(settings.DB_PATH,os.sep,self.id)
        pickle.dump(self,open(file_path,'wb'))

    @property
    def is_exists(self):
        tag=True
        files=os.listdir(settings.DB_PATH)
        for file in files:
            file_abspath=r'%s%s%s' %(settings.DB_PATH,os.sep,file)
            obj=pickle.load(open(file_abspath,'rb'))
            if self.host == obj.host and self.port == obj.port:
                tag=False
                break
        return tag
    @staticmethod
    def get_obj_by_id(id):
        file_abspath = r'%s%s%s' % (settings.DB_PATH, os.sep, id)
        return pickle.load(open(file_abspath,'rb'))

    @staticmethod
    def create_id():
        return str(uuid.uuid1())

    @classmethod
    def from_conf(cls):
        print(cls)
        return cls(settings.HOST,settings.PORT)

# print(MySQL.from_conf) #<bound method MySQL.from_conf of <class '__main__.MySQL'>>
conn=MySQL.from_conf()
conn.save()

conn1=MySQL('127.0.0.1',3306)
conn1.save() #拋出異常PermissionError: 對象已存在


obj=MySQL.get_obj_by_id('7e6c5ec0-7e9f-11e7-9acc-408d5c2f84ca')
print(obj.host)
練習1
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    @staticmethod
    def now(): #用Date.now()的形式去產生實例,該實例用的是當前時間
        t=time.localtime() #獲取結構化的時間格式
        return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建實例而且返回
    @staticmethod
    def tomorrow():#用Date.tomorrow()的形式去產生實例,該實例用的是明天的時間
        t=time.localtime(time.time()+86400)
        return Date(t.tm_year,t.tm_mon,t.tm_mday)

a=Date('1987',11,27) #本身定義時間
b=Date.now() #採用當前時間
c=Date.tomorrow() #採用明天的時間

print(a.year,a.month,a.day)
print(b.year,b.month,b.day)
print(c.year,c.month,c.day)


#分割線==============================
import time
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    @staticmethod
    def now():
        t=time.localtime()
        return Date(t.tm_year,t.tm_mon,t.tm_mday)

class EuroDate(Date):
    def __str__(self):
        return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)

e=EuroDate.now()
print(e) #咱們的意圖是想觸發EuroDate.__str__,可是結果爲
'''
輸出結果:
<__main__.Date object at 0x1013f9d68>
'''
由於e就是用Date類產生的,因此根本不會觸發EuroDate.__str__,解決方法就是用classmethod

import time
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    # @staticmethod
    # def now():
    #     t=time.localtime()
    #     return Date(t.tm_year,t.tm_mon,t.tm_mday)

    @classmethod #改爲類方法
    def now(cls):
        t=time.localtime()
        return cls(t.tm_year,t.tm_mon,t.tm_mday) #哪一個類來調用,即用哪一個類cls來實例化

class EuroDate(Date):
    def __str__(self):
        return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)

e=EuroDate.now()
print(e) #咱們的意圖是想觸發EuroDate.__str__,此時e就是由EuroDate產生的,因此會如咱們所願
'''
輸出結果:
year:2017 month:3 day:3
'''
練習2

 

屬性(@property)

屬性的介紹

Python中的屬性實際上是普通方法的變種。

對於屬性,有如下三個知識點:

  • 屬性的基本使用
  • 屬性的兩種定義方式
"""
由屬性的定義和調用要注意一下幾點:

定義時,在普通方法的基礎上添加 @property 裝飾器;
定義時,屬性僅有一個self參數
調用時,無需括號
           方法:foo_obj.func()
           屬性:foo_obj.prop
"""
# ############### 定義 ###############
class Foo:

    def func(self):
        pass

    # 定義屬性
    @property
    def prop(self):
        return "@property"
# ############### 調用 ###############
foo_obj = Foo()

foo_obj.func()
foo_obj.prop   #調用屬性
屬性的使用
"""
實例:對於主機列表頁面,每次請求不可能把數據庫中的全部內容都顯示到頁面上,而是經過分頁的功能局部顯示,因此在向數據庫中請求數據時就要顯示的指定獲取從第m條到第n條的全部數據(即:limit m,n),這個分頁的功能包括:

根據用戶請求的當前頁和總數據條數計算出 m 和 n
根據m 和 n 去數據庫中請求數據 
"""
# ############### 定義 ###############
class Pager:

    def __init__(self, current_page):
        # 用戶當前請求的頁碼(第一頁、第二頁...)
        self.current_page = current_page
        # 每頁默認顯示10條數據
        self.per_items = 10

    @property
    def start(self):
        val = (self.current_page - 1) * self.per_items
        return val

    @property
    def end(self):
        val = self.current_page * self.per_items
        return val


# ############### 調用 ###############

p = Pager(1)
p.start
# 就是起始值,即:m
p.end
# 就是結束值,即:n
@property的實例使用--分頁

屬性的定義

屬性的兩種定義方式:

  • 裝飾器 即:在方法上應用裝飾器
  • 靜態字段 即:在類中定義值爲property對象的靜態字段
注:經典類中的屬性只有一種訪問方式,其對應被 @property 修飾的方法
      新式類中的屬性有三種訪問方式,並分別對應了三個被@property、@方法名.setter、@方法名.deleter修飾的方法

因爲新式類中具備三種訪問方式,咱們能夠根據他們幾個屬性的訪問特色,分別將三個方法定義爲對同一個屬性:獲取、修改、刪除
# ############### 定義 ###############
class Goods(object):

    @property
    def price(self):
        print('@property')

    @price.setter
    def price(self, value):
        print('@price.setter')

    @price.deleter
    def price(self):
        print('@price.deleter')

# ############### 調用 ###############
obj = Goods()

obj.price          # 自動執行 @property 修飾的 price 方法,並獲取方法的返回值

obj.price = 123    # 自動執行 @price.setter 修飾的 price 方法,並將  123 賦值給方法的參數

del obj.price      # 自動執行 @price.deleter 修飾的 price 方法
裝飾器:@property、@property.setter、@property.deleter定義
class Goods(object):

    def __init__(self):
        # 原價
        self.original_price = 100
        # 折扣
        self.discount = 0.8

    @property
    def price(self):
        # 實際價格 = 原價 * 折扣
        new_price = self.original_price * self.discount
        return new_price

    @price.setter
    def price(self, value):
        self.original_price = value

    @price.deltter
    def price(self, value):
        del self.original_price

obj = Goods()
obj.price         # 獲取商品價格
obj.price = 200   # 修改商品原價
del obj.price     # 刪除商品原價
裝飾器:@property、@property.setter、@property.deleter實例
"""
property的構造方法中有個四個參數

第一個參數是方法名,調用 對象.屬性 時自動觸發執行方法
第二個參數是方法名,調用 對象.屬性 = XXX 時自動觸發執行方法
第三個參數是方法名,調用 del 對象.屬性 時自動觸發執行方法
第四個參數是字符串,調用 對象.屬性.__doc__ ,此參數是該屬性的描述信息
"""

class Foo:

    def get_bar(self):
        return 'wupeiqi'

    # *必須兩個參數
    def set_bar(self, value): 
        return return 'set value' + value

    def del_bar(self):
        return 'wupeiqi'

    BAR = property(get_bar, set_bar, del_bar, 'description...')

obj = Foo()

obj.BAR              # 自動調用第一個參數中定義的方法:get_bar
obj.BAR = "alex"     # 自動調用第二個參數中定義的方法:set_bar方法,並將「alex」看成參數傳入
del Foo.BAR          # 自動調用第三個參數中定義的方法:del_bar方法
obj.BAE.__doc__      # 自動獲取第四個參數中設置的值:description...
靜態方法property對象
class Goods(object):

    def __init__(self):
        # 原價
        self.original_price = 100
        # 折扣
        self.discount = 0.8

    def get_price(self):
        # 實際價格 = 原價 * 折扣
        new_price = self.original_price * self.discount
        return new_price

    def set_price(self, value):
        self.original_price = value

    def del_price(self, value):
        del self.original_price

    PRICE = property(get_price, set_price, del_price, '價格屬性描述...')

obj = Goods()
obj.PRICE         # 獲取商品價格
obj.PRICE = 200   # 修改商品原價
del obj.PRICE     # 刪除商品原價

實例
靜態方法property實例
class WSGIRequest(http.HttpRequest):
    def __init__(self, environ):
        script_name = get_script_name(environ)
        path_info = get_path_info(environ)
        if not path_info:
            # Sometimes PATH_INFO exists, but is empty (e.g. accessing
            # the SCRIPT_NAME URL without a trailing slash). We really need to
            # operate as if they'd requested '/'. Not amazingly nice to force
            # the path like this, but should be harmless.
            path_info = '/'
        self.environ = environ
        self.path_info = path_info
        self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/'))
        self.META = environ
        self.META['PATH_INFO'] = path_info
        self.META['SCRIPT_NAME'] = script_name
        self.method = environ['REQUEST_METHOD'].upper()
        _, content_params = cgi.parse_header(environ.get('CONTENT_TYPE', ''))
        if 'charset' in content_params:
            try:
                codecs.lookup(content_params['charset'])
            except LookupError:
                pass
            else:
                self.encoding = content_params['charset']
        self._post_parse_error = False
        try:
            content_length = int(environ.get('CONTENT_LENGTH'))
        except (ValueError, TypeError):
            content_length = 0
        self._stream = LimitedStream(self.environ['wsgi.input'], content_length)
        self._read_started = False
        self.resolver_match = None

    def _get_scheme(self):
        return self.environ.get('wsgi.url_scheme')

    def _get_request(self):
        warnings.warn('`request.REQUEST` is deprecated, use `request.GET` or '
                      '`request.POST` instead.', RemovedInDjango19Warning, 2)
        if not hasattr(self, '_request'):
            self._request = datastructures.MergeDict(self.POST, self.GET)
        return self._request

    @cached_property
    def GET(self):
        # The WSGI spec says 'QUERY_STRING' may be absent.
        raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '')
        return http.QueryDict(raw_query_string, encoding=self._encoding)
    
    # ############### 看這裏看這裏  ###############
    def _get_post(self):
        if not hasattr(self, '_post'):
            self._load_post_and_files()
        return self._post

    # ############### 看這裏看這裏  ###############
    def _set_post(self, post):
        self._post = post

    @cached_property
    def COOKIES(self):
        raw_cookie = get_str_from_wsgi(self.environ, 'HTTP_COOKIE', '')
        return http.parse_cookie(raw_cookie)

    def _get_files(self):
        if not hasattr(self, '_files'):
            self._load_post_and_files()
        return self._files

    # ############### 看這裏看這裏  ###############
    POST = property(_get_post, _set_post)
    
    FILES = property(_get_files)
    REQUEST = property(_get_request)

Django源碼
靜態方法:Django 的視圖中 request.POST 就是使用的靜態字段的方式建立的屬性
#實現類型檢測功能

#第一關:
class People:
    def __init__(self,name):
        self.name=name

    @property
    def name(self):
        return self.name

# p1=People('alex') #property自動實現了set和get方法屬於數據描述符,比實例屬性優先級高,因此你這面寫會觸發property內置的set,拋出異常


#第二關:修訂版

class People:
    def __init__(self,name):
        self.name=name #實例化就觸發property

    @property
    def name(self):
        # return self.name #無限遞歸
        print('get------>')
        return self.DouNiWan

    @name.setter
    def name(self,value):
        print('set------>')
        self.DouNiWan=value

    @name.deleter
    def name(self):
        print('delete------>')
        del self.DouNiWan

p1=People('alex') #self.name實際是存放到self.DouNiWan裏
print(p1.name)
print(p1.name)
print(p1.name)
print(p1.__dict__)

p1.name='egon'
print(p1.__dict__)

del p1.name
print(p1.__dict__)


#第三關:加上類型檢查
class People:
    def __init__(self,name):
        self.name=name #實例化就觸發property

    @property
    def name(self):
        # return self.name #無限遞歸
        print('get------>')
        return self.DouNiWan

    @name.setter
    def name(self,value):
        print('set------>')
        if not isinstance(value,str):
            raise TypeError('必須是字符串類型')
        self.DouNiWan=value

    @name.deleter
    def name(self):
        print('delete------>')
        del self.DouNiWan

p1=People('alex') #self.name實際是存放到self.DouNiWan裏
p1.name=1
@property的一些簡單使用

 

公有的和私有的類成員

類的全部成員在上一步驟中已經作了詳細的介紹,對於每個類的成員而言都有兩種形式:

  • 公有成員,在任何地方都能訪問
  • 私有成員,只有在類的內部才能方法
  • 非要訪問私有屬性的話,能夠經過 對象._類__屬性名

私有成員和公有成員的定義不一樣:私有成員命名時,前兩個字符是下劃線。(特殊成員除外,例如:__init__、__call__、__dict__等)

class C:

    name = "公有靜態字段"

    def func(self):
        print(C.name)

class D(C):

    def show(self):
        print(C.name)


C.name         # 類訪問

obj = C()
obj.func()     # 類內部能夠訪問

obj_son = D()
obj_son.show() # 派生類中能夠訪問
公有類字段
class C:

    __name = "公有靜態字段"

    def func(self):
        print(C.__name)

class D(C):

    def show(self):
        print(C.__name)


C.__name       # 類訪問            ==> 錯誤

obj = C()
obj.func()     # 類內部能夠訪問     ==> 正確

obj_son = D()
obj_son.show() # 派生類中能夠訪問   ==> 錯誤
私有類字段
class C:

    def __init__(self):
        self.foo = "公有字段"

    def func(self):
        print(self.foo) # 類內部訪問

class D(C):

    def show(self):
        print(self.foo)  # 派生類中訪問

obj = C()

obj.foo  # 經過對象訪問
obj.func()  # 類內部訪問

obj_son = D();
obj_son.show()  # 派生類中訪問
公有實例字段
class C:

    def __init__(self):
        self.__foo = "私有字段"

    def func(self):
        print(self.foo)  # 類內部訪問

class D(C):

    def show(self):
        print(self.foo)  # 派生類中訪問

obj = C()

obj.__foo  # 經過對象訪問    ==> 錯誤
obj.func()  # 類內部訪問        ==> 正確

obj_son = D();
obj_son.show()  # 派生類中訪問  ==> 錯誤
私有實例字段
class A:
    __N=0 #類的數據屬性就應該是共享的,可是語法上是能夠把類的數據屬性設置成私有的如__N,會變形爲_A__N
    def __init__(self):
        self.__X=10 #變形爲self._A__X
    def __foo(self): #變形爲_A__foo
        print('from A')
    def bar(self):
        self.__foo() #只有在類內部才能夠經過__foo的形式訪問到.

# A._A__N是能夠訪問到的,




#把fa定義成私有的,即__fa
class A:
    def __fa(self): #在定義時就變形爲_A__fa
        print('from A')
    def test(self):
        self.__fa() #只會與本身所在的類爲準,即調用_A__fa

class B(A):
    def __fa(self):  # _B__fa,所以不會與A衝突
        print('from B')

b=B()
b.test()
手動使用私有成員_X__xxx

 

高級用法

一些經常使用的屬性

類名.__name__# 類的名字(字符串)
類名.__doc__# 類的文檔字符串
類名.__base__# 類的第一個父類(在講繼承時會講)
類名.__bases__# 類全部父類構成的元組(在講繼承時會講)
類名.__dict__# 類的字典屬性
類名.__module__# 類定義所在的模塊
類名.mro()或__mro__  # 類的祖宗

實例對象.__class__# 實例對應的類(僅新式類中)
"""
類名.__name__# 類的名字(字符串)
類名.__doc__# 類的文檔字符串
類名.__base__# 類的第一個父類(在講繼承時會講)
類名.__bases__# 類全部父類構成的元組(在講繼承時會講)
類名.__dict__# 類的字典屬性
類名.__module__# 類定義所在的模塊
類名.mro()或__mro__  # 類的祖宗

實例對象.__class__# 實例對應的類(僅新式類中)
"""



class P1(object):
    pass
class P2(P1):
    pass

class P3(P2):
    pass
class P4(P3):
    pass
class P5(P2):
    pass

class P6():
    pass

class People(P5,P4):
    """this is __doc__"""

    country = 'China'

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

    def talk(self):
        print('%s is talking' % self.name)



p = People("tom",18)

print(People.__name__)  # People
print(People.__doc__)  # this is __doc__
print(People.__base__)  # <class '__main__.P5'>
print(People.__bases__)  # (<class '__main__.P5'>, <class '__main__.P4'>)
print(People.__dict__)  # {'__module__': '__main__', '__doc__': 'this is __doc__', '__name__': 'People', 'country': 'China', '__init__': <function People.__init__ at 0x04EF0780>, 'talk': <function People.talk at 0x04EF06F0>}
print(People.__module__)  # __main__
print(People.mro())  # [<class '__main__.People'>, <class '__main__.P5'>, <class '__main__.P4'>, <class '__main__.P3'>, <class '__main__.P2'>, <class '__main__.P1'>, <class 'object'>]

print(p.__class__)  # <class '__main__.People'>
一些經常使用的屬性

isinstance(obj,cls)和issubclass(sub,super)

class Foo(object):
    pass

obj = Foo()

isinstance(obj, Foo)  # True
isinstance(obj,cls)檢查是否obj是不是類 cls 的對象
class Foo(object):
    pass
 
class Bar(Foo):
    pass
 
issubclass(Bar, Foo)
issubclass(sub, super)檢查sub類是不是 super 類的派生類

反射hasattr/getattr/setattr/delattr

python面向對象中的反射:經過字符串的形式操做對象相關的屬性。python中的一切事物都是對象(均可以使用反射)

# 判斷object中有沒有一個name字符串對應的方法或屬性
def hasattr(*args, **kwargs):  # real signature unknown
    """
    Return whether the object has an attribute with the given name.

    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass

# 獲取object里名爲name的屬性/方法
def getattr(object, name, default=None):  # known special case of getattr
    """
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

# 設置對象x裏y屬性的值爲v
def setattr(x, y, v):  # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.

    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

# 刪除對象x的y屬性
def delattr(x, y):  # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.

    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass
hasattr/getattr/setattr/delattr定義
class BlackMedium:
    feature='Ugly'
    def __init__(self,name,addr):
        self.name=name
        self.addr=addr

    def sell_house(self):
        print('%s 黑中介賣房子啦,傻逼纔買呢,可是誰能證實本身不傻逼' %self.name)
    def rent_house(self):
        print('%s 黑中介租房子啦,傻逼才租呢' %self.name)

b1=BlackMedium('萬成置地','回龍觀天露園')

#檢測是否含有某屬性
print(hasattr(b1,'name'))
print(hasattr(b1,'sell_house'))

#獲取屬性
n=getattr(b1,'name')
print(n)
func=getattr(b1,'rent_house')
func()

# getattr(b1,'aaaaaaaa') #報錯
print(getattr(b1,'aaaaaaaa','不存在啊'))

#設置屬性
setattr(b1,'sb',True)
setattr(b1,'show_name',lambda self:self.name+'sb')
print(b1.__dict__)
print(b1.show_name(b1))

#刪除屬性
delattr(b1,'addr')
delattr(b1,'show_name')
delattr(b1,'show_name111')#不存在,則報錯

print(b1.__dict__)
hasattr/getattr/setattr/delattr使用示例
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys


def s1():
    print('s1')


def s2():
    print('s2')


this_module = sys.modules[__name__]

hasattr(this_module, 's1')
res = getattr(this_module, 's2')
res()
反射當前模塊成員

導入其餘模塊,利用反射查找該模塊是否存在某個方法

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def test():
    print('from the test')
module_test.py(其餘模塊)
#!/usr/bin/env python
# -*- coding:utf-8 -*-

"""
程序目錄:
    module_test.py
    index.py

當前文件:
    index.py
"""

import module_test as obj

# obj.test()

print(hasattr(obj, 'test'))

getattr(obj, 'test')()
導入其餘模塊,利用反射查找該模塊是否存在某個方法

__setattr__,__delattr__,__getattr__

class Foo:
    x=1
    def __init__(self,y):
        self.y=y

    def __getattr__(self, item):
        print('----> from getattr:你找的屬性不存在')


    def __setattr__(self, key, value):
        print('----> from setattr')
        # self.key=value #這就無限遞歸了,你好好想一想
        # self.__dict__[key]=value #應該使用它

    def __delattr__(self, item):
        print('----> from delattr')
        # del self.item #無限遞歸了
        self.__dict__.pop(item)

#__setattr__添加/修改屬性會觸發它的執行
f1=Foo(10)
print(f1.__dict__) # 由於你重寫了__setattr__,凡是賦值操做都會觸發它的運行,你啥都沒寫,就是根本沒賦值,除非你直接操做屬性字典,不然永遠沒法賦值
f1.z=3
print(f1.__dict__)

#__delattr__刪除屬性的時候會觸發
f1.__dict__['a']=3#咱們能夠直接修改屬性字典,來完成添加/修改屬性的操做
del f1.a
print(f1.__dict__)

#__getattr__只有在使用點調用屬性且屬性不存在的時候纔會觸發
f1.xxxxxx
__setattr__,__delattr__,__getattr__

二次加工標準類型(包裝)

 包裝:python爲你們提供了標準數據類型,以及豐富的內置方法,其實在不少場景下咱們都須要基於標準數據類型來定製咱們本身的數據類型,新增/改寫方法,這就用到了咱們剛學的繼承/派生知識(其餘的標準類型都可以經過下面的方式進行二次加工)

class List(list): #繼承list全部的屬性,也能夠派生出本身新的,好比append和mid
    def append(self, p_object):
        ' 派生本身的append:加上類型檢查'
        if not isinstance(p_object,int):
            raise TypeError('must be int')
        super().append(p_object)

    @property
    def mid(self):
        '新增本身的屬性'
        index=len(self)//2
        return self[index]

l=List([1,2,3,4])
print(l)
l.append(5)
print(l)
# l.append('1111111') #報錯,必須爲int類型

print(l.mid)

#其他的方法都繼承list的
l.insert(0,-123)
print(l)
l.clear()
print(l)
基於繼承,對list進行二次加工
class List(list):
    def __init__(self,item,tag=False):
        super().__init__(item)
        self.tag=tag
    def append(self, p_object):
        if not isinstance(p_object,str):
            raise TypeError
        super().append(p_object)
    def clear(self):
        if not self.tag:
            raise PermissionError
        super().clear()

l=List([1,2,3],False)
print(l)
print(l.tag)

l.append('saf')
print(l)

# l.clear() #異常

l.tag=True
l.clear()
對list的某個方法添加權限控制

受權:受權是包裝的一個特性, 包裝一個類型一般是對已存在的類型的一些定製,這種作法能夠新建,修改或刪除原有產品的功能。其它的則保持原樣。受權的過程,便是全部更新的功能都是由新類的某部分來處理,但已存在的功能就受權給對象的默認屬性。

實現受權的關鍵點就是覆蓋__getattr__方法

import time
class FileHandle:
    def __init__(self,filename,mode='r',encoding='utf-8'):
        self.file=open(filename,mode,encoding=encoding)
    def write(self,line):
        t=time.strftime('%Y-%m-%d %T')
        self.file.write('%s %s' %(t,line))

    def __getattr__(self, item):
        return getattr(self.file,item)

f1=FileHandle('b.txt','w+')
f1.write('你好啊')
f1.seek(0)
print(f1.read())
f1.close()
受權示範一
受權示範二
#練習一
class List:
    def __init__(self,seq):
        self.seq=seq

    def append(self, p_object):
        ' 派生本身的append加上類型檢查,覆蓋原有的append'
        if not isinstance(p_object,int):
            raise TypeError('must be int')
        self.seq.append(p_object)

    @property
    def mid(self):
        '新增本身的方法'
        index=len(self.seq)//2
        return self.seq[index]

    def __getattr__(self, item):
        return getattr(self.seq,item)

    def __str__(self):
        return str(self.seq)

l=List([1,2,3])
print(l)
l.append(4)
print(l)
# l.append('3333333') #報錯,必須爲int類型

print(l.mid)

#基於受權,得到insert方法
l.insert(0,-123)
print(l)





#練習二
class List:
    def __init__(self,seq,permission=False):
        self.seq=seq
        self.permission=permission
    def clear(self):
        if not self.permission:
            raise PermissionError('not allow the operation')
        self.seq.clear()

    def __getattr__(self, item):
        return getattr(self.seq,item)

    def __str__(self):
        return str(self.seq)
l=List([1,2,3])
# l.clear() #此時沒有權限,拋出異常


l.permission=True
print(l)
l.clear()
print(l)

#基於受權,得到insert方法
l.insert(0,-123)
print(l)
基於受權 對list進行受權練習

__getattribute__

class Foo:
    def __init__(self,x):
        self.x=x

    def __getattr__(self, item):
        print('執行的是我')
        # return self.__dict__[item]

f1=Foo(10)
print(f1.x)
f1.xxxxxx #不存在的屬性訪問,觸發__getattr__
回顧__getattr__,不存在的屬性纔會觸發__getattr__
class Foo:
    def __init__(self,x):
        self.x=x

    def __getattribute__(self, item):
        print('無論是否存在,我都會執行')

f1=Foo(10)
f1.x
f1.xxxxxx
__getattribute__,不管是否存在該屬性都會觸發__getattribute__
#_*_coding:utf-8_*_
__author__ = 'Linhaifeng'

class Foo:
    def __init__(self,x):
        self.x=x

    def __getattr__(self, item):
        print('執行的是我')
        # return self.__dict__[item]
    def __getattribute__(self, item):
        print('無論是否存在,我都會執行')
        raise AttributeError('哈哈')

f1=Foo(10)
f1.x
f1.xxxxxx

#當__getattribute__與__getattr__同時存在,只會執行__getattrbute__,除非__getattribute__在執行過程當中拋出異常AttributeError
__getattr__ 和 __getattribute__同時出現,__getattribute__是無條件執行的

__getattribute__的一些使用

class C(object):
    a = 'abc'
    def __init__(self,name):
        self.name = name

    def __getattribute__(self, *args, **kwargs):
        print("__getattribute__() is called")
        return object.__getattribute__(self, *args, **kwargs)

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

if __name__ == '__main__':
    c = C("Tom")

    print(c.name)
    print(c.a)
    c.test()
在獲取元素的同時添加一下額外的操做
class C(object):
    a = 'abc'
    def __getattribute__(self, *args, **kwargs):
        print("__getattribute__")
        raise AttributeError

    def __getattr__(self,item):
        print("__getattr__")
        

if __name__ == '__main__':
    c = C()

    print(c.foo)
    print(c.a)
在__getattribute__觸發AttributeError,從而觸發__getattr__
class C(object):
    a = 'abc'
    def __getattribute__(self, *args, **kwargs):
        print("__getattribute__")
        if args[0] == 'a':
            return object.__getattribute__(self, *args, **kwargs)
        else:
            print("除了上面的那些屬性,其他的均返回func方法")
            return object.__getattribute__(self,'func')()
    def func(self):
        print("do something")
        return "hello"
if __name__ == '__main__':
    c = C()

    print(c.a)
    c.xxx
    c.yyy

    #print c.a
使用__getattribute__控制只容許某些屬性/方法可使用,其餘的均返回固定的屬性/方法

描述符(__get__,__set__,__delete__)

描述符是什麼

描述符本質就是一個新式類,在這個新式類中,至少實現了__get__(),__set__(),__delete__()中的一個,這也被稱爲描述符協議
__get__():調用一個屬性時,觸發
__set__():爲一個屬性賦值時,觸發
__delete__():採用del刪除屬性時,觸發

class Foo: #在python3中Foo是新式類,它實現了三種方法,這個類就被稱做一個描述符
    def __get__(self, instance, owner):
        pass
    def __set__(self, instance, value):
        pass
    def __delete__(self, instance):
        pass
定義一個描述符

描述符是幹什麼的

描述符是幹什麼的:描述符的做用是用來代理另一個類的屬性的(必須把描述符定義成這個類的類屬性,不能定義到構造函數中)

class Foo:
    def __get__(self, instance, owner):
        print('觸發get')
    def __set__(self, instance, value):
        print('觸發set')
    def __delete__(self, instance):
        print('觸發delete')

#包含這三個方法的新式類稱爲描述符,由這個類產生的實例進行屬性的調用/賦值/刪除,並不會觸發這三個方法
f1=Foo()
f1.name='egon'
f1.name
del f1.name
#疑問:什麼時候,何地,會觸發這三個方法的執行
描述符類產生的實例進行屬性操做並不會觸發三個方法的執行
#描述符Str
class Str:
    def __get__(self, instance, owner):
        print('Str調用')
    def __set__(self, instance, value):
        print('Str設置...')
    def __delete__(self, instance):
        print('Str刪除...')

#描述符Int
class Int:
    def __get__(self, instance, owner):
        print('Int調用')
    def __set__(self, instance, value):
        print('Int設置...')
    def __delete__(self, instance):
        print('Int刪除...')

class People:
    name=Str()
    age=Int()
    def __init__(self,name,age): #name被Str類代理,age被Int類代理,
        self.name=name
        self.age=age

#何地?:定義成另一個類的類屬性

#什麼時候?:且看下列演示

p1=People('alex',18)

#描述符Str的使用
p1.name
p1.name='egon'
del p1.name

#描述符Int的使用
p1.age
p1.age=18
del p1.age

#咱們來瞅瞅到底發生了什麼
print(p1.__dict__)
print(People.__dict__)

#補充
print(type(p1) == People) #type(obj)實際上是查看obj是由哪一個類實例化來的
print(type(p1).__dict__ == People.__dict__)
把描述符的類放在目標類中做代理,進行get/set/del會觸發

數據描述符 和 非數據描述符

# 數據描述符:至少實現了__get__()和__set__()
class Foo:
    def __set__(self, instance, value):
        print('set')
    def __get__(self, instance, owner):
        print('get')

# 非數據描述符:沒有實現__set__()
class Foo:
    def __get__(self, instance, owner):
        print('get')
數據描述符 和 非數據描述符

類屬性的優先級(涉及描述符)

注意事項:
一 描述符自己應該定義成新式類,被代理的類也應該是新式類
二 必須把描述符定義成這個類的類屬性,不能爲定義到構造函數中
三 要嚴格遵循該優先級,優先級由高到底分別是
1.類屬性
2.數據描述符
3.實例屬性
4.非數據描述符
5.找不到的屬性觸發__getattr__()

#描述符Str
class Str:
    def __get__(self, instance, owner):
        print('Str調用')
    def __set__(self, instance, value):
        print('Str設置...')
    def __delete__(self, instance):
        print('Str刪除...')

class People:
    name=Str()
    def __init__(self,name,age): #name被Str類代理,age被Int類代理,
        self.name=name
        self.age=age


#基於上面的演示,咱們已經知道,在一個類中定義描述符它就是一個類屬性,存在於類的屬性字典中,而不是實例的屬性字典

#那既然描述符被定義成了一個類屬性,直接經過類名也必定能夠調用吧,沒錯
People.name #恩,調用類屬性name,本質就是在調用描述符Str,觸發了__get__()

People.name='egon' #那賦值呢,我去,並無觸發__set__(),由於從新定義了類屬性,覆蓋了描述符
del People.name #趕忙試試del,我去,也沒有觸發__delete__()
#結論:描述符對類沒有做用-------->傻逼到家的結論

'''
緣由:描述符在使用時被定義成另一個類的類屬性,於是類屬性比二次加工的描述符假裝而來的類屬性有更高的優先級
People.name #恩,調用類屬性name,找不到就去找描述符假裝的類屬性name,觸發了__get__()

People.name='egon' #那賦值呢,直接賦值了一個類屬性,它擁有更高的優先級,至關於覆蓋了描述符,確定不會觸發描述符的__set__()
del People.name #同上
'''

# 類屬性>數據描述符
類屬性>數據描述符
#描述符Str
class Str:
    def __get__(self, instance, owner):
        print('Str調用')
    def __set__(self, instance, value):
        print('Str設置...')
    def __delete__(self, instance):
        print('Str刪除...')

class People:
    name=Str()
    def __init__(self,name,age): #name被Str類代理,age被Int類代理,
        self.name=name
        self.age=age


p1=People('egon',18)
print(p1.name)  # None,描述符優先
#若是描述符是一個數據描述符(即有__get__又有__set__),那麼p1.name的調用與賦值都是觸發描述符的操做,於p1自己無關了,至關於覆蓋了實例的屬性
p1.name='egonnnnnn'
p1.name
print(p1.__dict__)#實例的屬性字典中沒有name,由於name是一個數據描述符,優先級高於實例屬性,查看/賦值/刪除都是跟描述符有關,與實例無關了
del p1.name
數據描述符>實例屬性
class Foo:
    def func(self):
        print('我胡漢三又回來了')
f1=Foo()
f1.func() #調用類的方法,也能夠說是調用非數據描述符
#函數是一個非數據描述符對象(一切皆對象麼)
print(dir(Foo.func))
print(hasattr(Foo.func,'__set__'))  # False
print(hasattr(Foo.func,'__get__'))  # True
print(hasattr(Foo.func,'__delete__'))  # False
#有人可能會問,描述符不都是類麼,函數怎麼算也應該是一個對象啊,怎麼就是描述符了
#笨蛋哥,描述符是類沒問題,描述符在應用的時候不都是實例化成一個類屬性麼
#函數就是一個由非描述符類實例化獲得的對象
#沒錯,字符串也同樣


f1.func='這是實例屬性啊'
print(f1.func)

del f1.func #刪掉了非數據
f1.func()
實例屬性>非數據描述符
class Foo:
    def __set__(self, instance, value):
        print('set')
    def __get__(self, instance, owner):
        print('get')
class Room:
    name=Foo()
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length


#name是一個數據描述符,由於name=Foo()而Foo實現了get和set方法,於是比實例屬性有更高的優先級
#對實例的屬性操做,觸發的都是描述符的
r1=Room('廁所',1,1)
r1.name
r1.name='廚房'



class Foo:
    def __get__(self, instance, owner):
        print('get')
class Room:
    name=Foo()
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length


#name是一個非數據描述符,由於name=Foo()而Foo沒有實現set方法,於是比實例屬性有更低的優先級
#對實例的屬性操做,觸發的都是實例本身的
r1=Room('廁所',1,1)
r1.name
r1.name='廚房'
再次驗證:實例屬性>非數據描述符
class Foo:
    def func(self):
        print('我胡漢三又回來了')

    def __getattr__(self, item):
        print('找不到了固然是來找我啦',item)
f1=Foo()

f1.xxxxxxxxxxx
# 找不到了固然是來找我啦 xxxxxxxxxxx
非數據描述符>找不到

描述符使用

class Str:
    def __init__(self,name):
        self.name=name
    def __get__(self, instance, owner):
        print('get--->',instance,owner)
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print('set--->',instance,value)
        instance.__dict__[self.name]=value
    def __delete__(self, instance):
        print('delete--->',instance)
        instance.__dict__.pop(self.name)


class People:
    name=Str('name')
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

p1=People('tom',18,3000)

#調用
print(p1.__dict__)
p1.name

#賦值
print(p1.__dict__)
p1.name='lily'
print(p1.__dict__)

#刪除
print(p1.__dict__)
del p1.name
print(p1.__dict__)

# 牛刀小試
"""
set---> <__main__.People object at 0x05508D70> tom
{'name': 'tom', 'age': 18, 'salary': 3000}
get---> <__main__.People object at 0x05508D70> <class '__main__.People'>
{'name': 'tom', 'age': 18, 'salary': 3000}
set---> <__main__.People object at 0x05508D70> lily
{'name': 'lily', 'age': 18, 'salary': 3000}
{'name': 'lily', 'age': 18, 'salary': 3000}
delete---> <__main__.People object at 0x05508D70>
{'age': 18, 'salary': 3000}
"""


# 小試牛刀  使用描述符爲對象屬性增長效果
小試牛刀 使用描述符爲實例對象屬性增長效果
class Str:
    def __init__(self,name):
        self.name=name
    def __get__(self, instance, owner):
        print('get--->',instance,owner)
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print('set--->',instance,value)
        instance.__dict__[self.name]=value
    def __delete__(self, instance):
        print('delete--->',instance)
        instance.__dict__.pop(self.name)


class People:
    name=Str('name')
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

#疑問:若是我用類名去操做屬性呢
# People.name #報錯,錯誤的根源在於類去操做屬性時,會把None傳給instance

#修訂__get__方法
class Str:
    def __init__(self,name):
        self.name=name
    def __get__(self, instance, owner):
        print('get--->',instance,owner)
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print('set--->',instance,value)
        instance.__dict__[self.name]=value
    def __delete__(self, instance):
        print('delete--->',instance)
        instance.__dict__.pop(self.name)


class People:
    name=Str('name')
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary
print(People.name) #完美,解決

"""
get---> None <class '__main__.People'>
<__main__.Str object at 0x04BC8D90>
"""
拔刀相助 類調用描述符屬性
class Str:
    def __init__(self,name,expected_type):
        self.name=name
        self.expected_type=expected_type
    def __get__(self, instance, owner):
        print('get--->',instance,owner)
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print('set--->',instance,value)
        if not isinstance(value,self.expected_type): #若是不是指望的類型,則拋出異常
            raise TypeError('Expected %s' %str(self.expected_type))
        instance.__dict__[self.name]=value
    def __delete__(self, instance):
        print('delete--->',instance)
        instance.__dict__.pop(self.name)


class People:
    name=Str('name',str) #新增類型限制str
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

p1=People(123,18,3333.3)#傳入的name因不是字符串類型而拋出異常


"""
set---> <__main__.People object at 0x059F8510> 123
Traceback (most recent call last):
  File "D:/Python相關/項目/interview/test.py", line 28, in <module>
    p1=People(123,18,3333.3)#傳入的name因不是字符串類型而拋出異常
  File "D:/Python相關/項目/interview/test.py", line 24, in __init__
    self.name=name
  File "D:/Python相關/項目/interview/test.py", line 14, in __set__
    raise TypeError('Expected %s' %str(self.expected_type))
TypeError: Expected <class 'str'>
"""
磨刀霍霍 控制__set__中value的type
class Typed:
    def __init__(self,name,expected_type):
        self.name=name
        self.expected_type=expected_type

    def __get__(self, instance, owner):
        print('get--->',instance,owner)
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print('set--->',instance,value)
        if not isinstance(value,self.expected_type):
            raise TypeError('Expected %s' %str(self.expected_type))
        instance.__dict__[self.name]=value
    def __delete__(self, instance):
        print('delete--->',instance)
        instance.__dict__.pop(self.name)


class People:
    name=Typed('name',str)
    age=Typed('age',int)
    salary=Typed('salary',float)
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

p1=People("p1",18,3333.3)
p2=People('p2',18,3333.3)
p3=People('p3',18,3333.3)

print(p1.name,p1.age,p1.salary)
大刀闊斧 多個類屬性使用描述符

終極,使用類的裝飾器在類裏使用描述符,避免上面那樣一個一個定義

def decorate(cls):
    print('類的裝飾器開始運行啦------>')
    return cls

@decorate #無參:People=decorate(People)
class People:
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

p1=People('tom',18,3333.3)
前言:類的裝飾器:無參
def typeassert(**kwargs):
    def decorate(cls):
        print('類的裝飾器開始運行啦------>',kwargs)
        return cls
    return decorate
@typeassert(name=str,age=int,salary=float) #有參:1.運行typeassert(...)返回結果是decorate,此時參數都傳給kwargs 2.People=decorate(People)
class People:
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

p1=People('tom',18,3333.3)
前言:類的裝飾器:有參
class Typed:
    def __init__(self,name,expected_type):
        self.name=name
        self.expected_type=expected_type
    def __get__(self, instance, owner):
        print('get--->',instance,owner)
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        print('set--->',instance,value)
        if not isinstance(value,self.expected_type):
            raise TypeError('Expected %s' %str(self.expected_type))
        instance.__dict__[self.name]=value
    def __delete__(self, instance):
        print('delete--->',instance)
        instance.__dict__.pop(self.name)

def typeassert(**kwargs):
    def decorate(cls):
        print('類的裝飾器開始運行啦------>',kwargs)
        for name,expected_type in kwargs.items():
            setattr(cls,name,Typed(name,expected_type))
        return cls
    return decorate
@typeassert(name=str,age=int,salary=float) #有參:1.運行typeassert(...)返回結果是decorate,此時參數都傳給kwargs 2.People=decorate(People)
class People:
    def __init__(self,name,age,salary):
        self.name=name
        self.age=age
        self.salary=salary

print(People.__dict__)
p1=People('egon',18,3333.3)
終極

利用描述符自制property/classmethod/staticmethod

class Lazyproperty:
    def __init__(self,func):
        self.func=func
    def __get__(self, instance, owner):
        print('這是咱們本身定製的靜態屬性,r1.area實際是要執行r1.area()')
        if instance is None:
            return self
        return self.func(instance) #此時你應該明白,究竟是誰在爲你作自動傳遞self的事情

class Room:
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length

    @Lazyproperty #area=Lazyproperty(area) 至關於定義了一個類屬性,即描述符
    def area(self):
        return self.width * self.length

r1=Room('alex',1,1)
print(r1.area)
本身作一個@property
class Lazyproperty:
    def __init__(self,func):
        self.func=func
    def __get__(self, instance, owner):
        print('這是咱們本身定製的靜態屬性,r1.area實際是要執行r1.area()')
        if instance is None:
            return self
        else:
            print('--->')
            value=self.func(instance)
            setattr(instance,self.func.__name__,value) #計算一次就緩存到實例的屬性字典中
            return value

class Room:
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length

    @Lazyproperty #area=Lazyproperty(area) 至關於'定義了一個類屬性,即描述符'
    def area(self):
        return self.width * self.length

r1=Room('alex',1,1)
print(r1.area) #先從本身的屬性字典找,沒有再去類的中找,而後出發了area的__get__方法
# 1
r1.width = 2
r1.length = 3
print(r1.area) #先從本身的屬性字典找,找到了,是上次計算的結果,這樣就不用每執行一次都去計算
# 1
print(r1.__dict__)
# {'name': 'alex', 'width': 2, 'length': 3, 'area': 1}


# property實現實現延遲計算功能,計算結果緩存到__dict__
property實現實現延遲計算功能,計算結果緩存到__dict__,因爲使用非數據描述符,實例屬性優先,所以從__dict__取數據
#緩存不起來了

class Lazyproperty:
    def __init__(self,func):
        self.func=func
    def __get__(self, instance, owner):
        print('這是咱們本身定製的靜態屬性,r1.area實際是要執行r1.area()')
        if instance is None:
            return self
        else:
            value=self.func(instance)
            instance.__dict__[self.func.__name__]=value
            return value
        # return self.func(instance) #此時你應該明白,究竟是誰在爲你作自動傳遞self的事情
    def __set__(self, instance, value):
        print('hahahahahah')

class Room:
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length

    @Lazyproperty #area=Lazyproperty(area) 至關於定義了一個類屬性,即描述符
    def area(self):
        return self.width * self.length

print(Room.__dict__)
r1=Room('alex',1,1)
print(r1.area)
print(r1.area) 
print(r1.area)

r1.width = 2
r1.length = 3
print(r1.area) #緩存功能失效,每次都去找描述符了,爲什麼,由於描述符實現了set方法,它由非數據描述符變成了數據描述符,數據描述符比實例屬性有更高的優先級,於是全部的屬性操做都去找描述符了
property實現實現延遲計算功能,因爲使用數據描述符(比實例屬性優先)每次調用都是先調用描述符,計算結果緩存到__dict__但沒用途
class ClassMethod:
    def __init__(self,func):
        self.func=func

    def __get__(self, instance, owner): #類來調用,instance爲None,owner爲類自己,實例來調用,instance爲實例,owner爲類自己,
        def feedback():
            print('在這裏能夠加功能啊...')
            return self.func(owner)
        return feedback

class People:
    name='linhaifeng'
    @ClassMethod # say_hi=ClassMethod(say_hi)
    def say_hi(cls):
        print('你好啊,帥哥 %s' %cls.name)

People.say_hi()

p1=People()
p1.say_hi()
#疑問,類方法若是有參數呢,好說,好說

class ClassMethod:
    def __init__(self,func):
        self.func=func

    def __get__(self, instance, owner): #類來調用,instance爲None,owner爲類自己,實例來調用,instance爲實例,owner爲類自己,
        def feedback(*args,**kwargs):
            print('在這裏能夠加功能啊...')
            return self.func(owner,*args,**kwargs)
        return feedback

class People:
    name='linhaifeng'
    @ClassMethod # say_hi=ClassMethod(say_hi)
    def say_hi(cls,msg):
        print('你好啊,帥哥 %s %s' %(cls.name,msg))

People.say_hi('你是那偷心的賊')

p1=People()
p1.say_hi('你是那偷心的賊')
本身作一個@classmethod
class StaticMethod:
    def __init__(self,func):
        self.func=func

    def __get__(self, instance, owner): #類來調用,instance爲None,owner爲類自己,實例來調用,instance爲實例,owner爲類自己,
        def feedback(*args,**kwargs):
            print('在這裏能夠加功能啊...')
            return self.func(*args,**kwargs)
        return feedback

class People:
    @StaticMethod# say_hi=StaticMethod(say_hi)
    def say_hi(x,y,z):
        print('------>',x,y,z)

People.say_hi(1,2,3)

p1=People()
p1.say_hi(4,5,6)
本身作一個@staticmethod

描述符總結

描述符是能夠實現大部分python類特性中的底層魔法,包括@classmethod,@staticmethd,@property甚至是__slots__屬性

描述父是不少高級庫和框架的重要工具之一,描述符一般是使用到裝飾器或者元類的大型框架中的一個組件.

__setitem__,__getitem,__delitem__

可記憶爲dict裏有items這個方法,所以操做起來像操做dict。

class Foo:
    def __init__(self,name):
        self.name=name

    def __getitem__(self, item):
        print(self.__dict__[item])

    def __setitem__(self, key, value):
        self.__dict__[key]=value
    def __delitem__(self, key):
        print('del obj[key]時,我執行')
        self.__dict__.pop(key)
    def __delattr__(self, item):
        print('del obj.key時,我執行')
        self.__dict__.pop(item)

f1=Foo('sb')
f1['age']=18
f1['age1']=19
del f1.age1
del f1['age']
f1['name']='alex'
print(f1.__dict__)
__setitem__,__getitem,__delitem__(可記憶爲dict裏有items這個方法,所以操做起來像操做dict)

實戰

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import uuid
import json
from flask.sessions import SessionInterface
from flask.sessions import SessionMixin
from itsdangerous import Signer, BadSignature, want_bytes


class MySession(dict, SessionMixin):
    def __init__(self, initial=None, sid=None):
        self.sid = sid
        self.initial = initial
        super(MySession, self).__init__(initial or ())


    def __setitem__(self, key, value):
        super(MySession, self).__setitem__(key, value)

    def __getitem__(self, item):
        return super(MySession, self).__getitem__(item)

    def __delitem__(self, key):
        super(MySession, self).__delitem__(key)



class MySessionInterface(SessionInterface):
    session_class = MySession
    container = {}

    def __init__(self):
        import redis
        self.redis = redis.Redis()

    def _generate_sid(self):
        return str(uuid.uuid4())

    def _get_signer(self, app):
        if not app.secret_key:
            return None
        return Signer(app.secret_key, salt='flask-session',
                      key_derivation='hmac')

    def open_session(self, app, request):
        """
        程序剛啓動時執行,須要返回一個session對象
        """
        sid = request.cookies.get(app.session_cookie_name)
        if not sid:
            sid = self._generate_sid()
            return self.session_class(sid=sid)

        signer = self._get_signer(app)
        try:
            sid_as_bytes = signer.unsign(sid)
            sid = sid_as_bytes.decode()
        except BadSignature:
            sid = self._generate_sid()
            return self.session_class(sid=sid)

        # session保存在redis中
        # val = self.redis.get(sid)
        # session保存在內存中
        val = self.container.get(sid)

        if val is not None:
            try:
                data = json.loads(val)
                return self.session_class(data, sid=sid)
            except:
                return self.session_class(sid=sid)
        return self.session_class(sid=sid)

    def save_session(self, app, session, response):
        """
        程序結束前執行,能夠保存session中全部的值
        如:
            保存到resit
            寫入到用戶cookie
        """
        domain = self.get_cookie_domain(app)
        path = self.get_cookie_path(app)
        httponly = self.get_cookie_httponly(app)
        secure = self.get_cookie_secure(app)
        expires = self.get_expiration_time(app, session)

        val = json.dumps(dict(session))

        # session保存在redis中
        # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime)
        # session保存在內存中
        self.container.setdefault(session.sid, val)

        session_id = self._get_signer(app).sign(want_bytes(session.sid))

        response.set_cookie(app.session_cookie_name, session_id,
                            expires=expires, httponly=httponly,
                            domain=domain, path=path, secure=secure)

# =========================================

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.session_interface = MySessionInterface()
自定義session

__getslice__、__setslice__、__delslice__

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
class Foo(object):
 
    def __getslice__(self, i, j):
        print '__getslice__',i,j
 
    def __setslice__(self, i, j, sequence):
        print '__setslice__',i,j
 
    def __delslice__(self, i, j):
        print '__delslice__',i,j
 
obj = Foo()
 
obj[-1:1]                   # 自動觸發執行 __getslice__
obj[0:1] = [11,22,33,44]    # 自動觸發執行 __setslice__
del obj[0:2]                # 自動觸發執行 __delslice__
該三個方法用於分片操做,如:列表

__str__,__repr__,

改變對象的字符串顯示__str__,__repr__

class School:
    def __init__(self,name,addr,type):
        self.name=name
        self.addr=addr
        self.type=type

    def __str__(self):
        return '__str__:(%s,%s)' %(self.name,self.addr)
    
    def __repr__(self):
        return '__repr__:School(%s,%s)' %(self.name,self.addr)


s = School("北京大學","五道口","本科")

print('from str: ',str(s))
print('from repr: ',repr(s))

print(s)
print([s])
__str__,__repr__

__format__

自定製格式化字符串__format__

#_*_coding:utf-8_*_
format_dict={
    'nat':'{obj.name}-{obj.addr}-{obj.type}',#學校名-學校地址-學校類型
    'tna':'{obj.type}:{obj.name}:{obj.addr}',#學校類型:學校名:學校地址
    'tan':'{obj.type}/{obj.addr}/{obj.name}',#學校類型/學校地址/學校名
}
class School:
    def __init__(self,name,addr,type):
        self.name=name
        self.addr=addr
        self.type=type

    def __format__(self, format_spec):
        # if format_spec
        if not format_spec or format_spec not in format_dict:
            format_spec='nat'
        fmt=format_dict[format_spec]
        return fmt.format(obj=self)

s1=School('oldboy1','北京','私立')

'''
str函數或者print函數--->obj.__str__()
repr或者交互式解釋器--->obj.__repr__()
若是__str__沒有被定義,那麼就會使用__repr__來代替輸出
注意:這倆方法的返回值必須是字符串,不然拋出異常
'''
print(format(s1,'nat'))
print(format(s1,'tna'))
print(format(s1,'tan'))
print(format(s1,'asfdasdffd'))
print(format(s1))
__format__實例
date_dic={
    'ymd':'{0.year}:{0.month}:{0.day}',
    'dmy':'{0.day}/{0.month}/{0.year}',
    'mdy':'{0.month}-{0.day}-{0.year}',
}
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day

    def __format__(self, format_spec):
        if not format_spec or format_spec not in date_dic:
            format_spec='ymd'
        fmt=date_dic[format_spec]
        return fmt.format(self)

d1=Date(2016,12,29)
print(format(d1))
print('{:mdy}'.format(d1))

自定義format練習
__format__練習

__slots__

'''
1.__slots__是什麼:是一個類變量,變量值能夠是列表,元祖,或者可迭代對象,也能夠是一個字符串(意味着全部實例只有一個數據屬性)
2.引子:使用點來訪問屬性本質就是在訪問類或者對象的__dict__屬性字典(類的字典是共享的,而每一個實例的是獨立的)
3.爲什麼使用__slots__:字典會佔用大量內存,若是你有一個屬性不多的類,可是有不少實例,爲了節省內存可使用__slots__取代實例的__dict__
當你定義__slots__後,__slots__就會爲實例使用一種更加緊湊的內部表示。實例經過一個很小的固定大小的數組來構建,而不是爲每一個實例定義一個
字典,這跟元組或列表很相似。在__slots__中列出的屬性名在內部被映射到這個數組的指定小標上。使用__slots__一個很差的地方就是咱們不能再給
實例添加新的屬性了,只能使用在__slots__中定義的那些屬性名。
4.注意事項:__slots__的不少特性都依賴於普通的基於字典的實現。另外,定義了__slots__後的類再也不 支持一些普通類特性了,好比多繼承。大多數狀況下,你應該
只在那些常常被使用到 的用做數據結構的類上定義__slots__好比在程序中須要建立某個類的幾百萬個實例對象 。
關於__slots__的一個常見誤區是它能夠做爲一個封裝工具來防止用戶給實例增長新的屬性。儘管使用__slots__能夠達到這樣的目的,可是這個並非它的初衷。           更多的是用來做爲一個內存優化工具。

'''
class Foo:
    __slots__='x'


f1=Foo()
f1.x=1
f1.y=2#報錯
print(f1.__slots__) #f1再也不有__dict__

class Bar:
    __slots__=['x','y']
    
n=Bar()
n.x,n.y=1,2
n.z=3#報錯

__slots__使用
__slots__使用,實例obj只容許使用__slots__裏面的元素
class Foo:
    __slots__=['name','age']

f1=Foo()
f1.name='alex'
f1.age=18
print(f1.__slots__)

f2=Foo()
f2.name='egon'
f2.age=19
print(f2.__slots__)

# print(f1.__dict__)  # 報錯
# print(f2.__dict__)  # 報錯

print(Foo.__dict__)
#f1與f2都沒有屬性字典__dict__了,統一歸__slots__管,節省內存
配置了__slots__的類,實例obj只容許使用__slots__裏面的元素,連__dict__等都沒有,只有類有。

__next__和__iter__實現迭代器協議

#_*_coding:utf-8_*_

class Foo:
    def __init__(self,x):
        self.x=x

    def __iter__(self):
        return self

    def __next__(self):
        self.x+=1
        return self.x

f=Foo(3)
for i in f:
    print(i)
簡單示例
class Foo:
    def __init__(self,start,stop):
        self.num=start
        self.stop=stop
    def __iter__(self):
        return self
    def __next__(self):
        if self.num >= self.stop:
            raise StopIteration
        n=self.num
        self.num+=1
        return n

f=Foo(1,5)
from collections import Iterable,Iterator
print(isinstance(f,Iterator))

for i in Foo(1,5):
    print(i)
簡單示例2
class Range:
    def __init__(self,n,stop,step):
        self.n=n
        self.stop=stop
        self.step=step

    def __next__(self):
        if self.n >= self.stop:
            raise StopIteration
        x=self.n
        self.n+=self.step
        return x

    def __iter__(self):
        return self

for i in Range(1,7,3): #
    print(i)
簡單模擬range,加上步長
class Fib:
    def __init__(self):
        self._a=0
        self._b=1

    def __iter__(self):
        return self

    def __next__(self):
        self._a,self._b=self._b,self._a + self._b
        return self._a

f1=Fib()

print(f1.__next__())
print(next(f1))
print(next(f1))

for i in f1:
    if i > 100:
        break
    print('%s ' %i,end='')
斐波那契數列

__doc__

class Foo:
    '我是描述信息'
    pass

class Bar(Foo):
    pass

print(Foo.__doc__)
print(Bar.__doc__) #該屬性沒法繼承給子類
類的描述信息,沒法被繼承

__module__和__class__

__module__ 表示當前操做的對象在那個模塊

__class__     表示當前操做的對象的類是什麼

#!/usr/bin/env python
# -*- coding:utf-8 -*-

class C:

    def __init__(self):
        self.name = ‘SB'
lib/aa.py
from lib.aa import C

obj = C()
print obj.__module__  # 輸出 lib.aa,即:輸出模塊
print obj.__class__      # 輸出 lib.aa.C,即:輸出類
index.py

__del__

析構方法,當對象在內存中被釋放時,自動觸發執行。

注:若是產生的對象僅僅只是python程序級別的(用戶級),那麼無需定義__del__,若是產生的對象的同時還會向操做系統發起系統調用,即一個對象有用戶級與內核級兩種資源,好比(打開一個文件,建立一個數據庫連接),則必須在清除對象的同時回收系統資源,這就用到了__del__

class Foo:

    def __del__(self):
        print('執行我啦')

f1=Foo()
del f1
print('------->')

#輸出結果
執行我啦
------->
手動del,觸發__del__
class Foo:

    def __del__(self):
        print('執行我啦')

f1=Foo()
# del f1
print('------->')

#輸出結果
------->
執行我啦

# 這是由於最後系統自動刪除,最後才觸發的__del__
系統最後回收資源,觸發__del__

典型的應用場景:

建立數據庫類,用該類實例化出數據庫連接對象,對象自己是存放於用戶空間內存中,而連接則是由操做系統管理的,存放於內核空間內存中

當程序結束時,python只會回收本身的內存空間,即用戶態內存,而操做系統的資源則沒有被回收,這就須要咱們定製__del__,在對象被刪除前向操做系統發起關閉數據庫連接的系統調用,回收資源

這與文件處理是一個道理:

f=open('a.txt') #作了兩件事,在用戶空間拿到一個f變量,在操做系統內核空間打開一個文件
del f #只回收用戶空間的f,操做系統的文件還處於打開狀態

#因此咱們應該在del f以前保證f.close()執行,即使是沒有del,程序執行完畢也會自動del清理資源,因而文件操做的正確用法應該是
f=open('a.txt')
讀寫...
f.close()
不少狀況下你們都容易忽略f.close,這就用到了with上下文管理
f文件處理,f.close,del f

__enter__和__exit__

咱們知道在操做文件對象的時候能夠這麼寫

with open('a.txt') as f:
  '代碼塊'

上述叫作上下文管理協議,即with語句,爲了讓一個對象兼容with語句,必須在這個對象的類中聲明__enter__和__exit__方法

使用

class Open:
    def __init__(self,name):
        self.name=name

    def __enter__(self):
        print('出現with語句,對象的__enter__被觸發,有返回值則賦值給as聲明的變量')
        # return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with中代碼塊執行完畢時執行我啊')


with Open('a.txt') as f:
    print('=====>執行代碼塊')
    # print(f,f.name)
上下文管理協議,帶__enter__,__exit__
class Open:
    def __init__(self,name):
        self.name=name

    def __enter__(self):
        print('出現with語句,對象的__enter__被觸發,有返回值則賦值給as聲明的變量')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with中代碼塊執行完畢時執行我啊')
        print(exc_type)
        print(exc_val)
        print(exc_tb)



with Open('a.txt') as f:
    print('=====>執行代碼塊')
    raise AttributeError('***着火啦,救火啊***')
print('0'*100) #------------------------------->不會執行

# print(exc_type)  # <class 'AttributeError'>
# print(exc_val)  # ***着火啦,救火啊***
# print(exc_tb)  # <traceback object at 0x093967B0>
__exit__()中的三個參數分別表明異常類型,異常值和追溯信息,with語句中代碼塊出現異常,則with後的代碼都沒法執行
class Open:
    def __init__(self,name):
        self.name=name

    def __enter__(self):
        print('出現with語句,對象的__enter__被觸發,有返回值則賦值給as聲明的變量')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('with中代碼塊執行完畢時執行我啊')
        print(exc_type)
        print(exc_val)
        print(exc_tb)
        return True



with Open('a.txt') as f:
    print('=====>執行代碼塊')
    raise AttributeError('***着火啦,救火啊***')
print('0'*100) #------------------------------->會執行
__exit__帶返回值True,則異常會清空,代碼繼續執行
class Open:
    def __init__(self,filepath,mode='r',encoding='utf-8'):
        self.filepath=filepath
        self.mode=mode
        self.encoding=encoding

    def __enter__(self):
        # print('enter')
        self.f=open(self.filepath,mode=self.mode,encoding=self.encoding)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        # print('exit')
        self.f.close()
        return True 
    def __getattr__(self, item):
        return getattr(self.f,item)

with Open('a.txt','w') as f:
    print(f)
    f.write('aaaaaa')
    f.wasdf #拋出異常,交給__exit__處理
練習:模擬Open
用途或者說好處:

1.使用with語句的目的就是把代碼塊放入with中執行,with結束後,自動完成清理工做,無須手動干預

2.在須要管理一些資源好比文件,網絡鏈接和鎖的編程環境中,能夠在__exit__中定製自動釋放資源的機制,你無須再去關係這個問題,這將大有用處

__call__

對象後面加括號,觸發執行。

注:構造方法的執行是由建立對象觸發的,即:對象 = 類名() ;而對於 __call__ 方法的執行是由對象後加括號觸發的,即:對象() 或者 類()()

class Foo:

    def __init__(self):
        pass
    
    def __call__(self, *args, **kwargs):

        print('__call__')


obj = Foo() # 執行 __init__
obj()       # 執行 __call__
__call__

用type建立類

class Foo(object):
    pass


f = Foo()

print(type(f))  # <class '__main__.Foo'>
print(type(Foo))  # <class 'type'>
obj對象是Foo類的一個實例,Foo類對象是 type 類的一個實例,即:Foo類對象 是經過type類的構造方法建立
class Foo(object):
 
    def func(self):
        print 'hello wupeiqi'
類建立的普通方法
def func(self):
    print 'hello wupeiqi'
 
Foo = type('Foo',(object,), {'func': func})
#type第一個參數:類名
#type第二個參數:當前類的基類
#type第三個參數:類的成員
類建立的 特殊方式(type類的構造函數)

 

metaclass

類默認是由 type 類實例化產生,type類中如何實現的建立類?類又是如何建立對象?

答:類中有一個屬性 __metaclass__,其用來表示該類由 誰 來實例化建立,因此,咱們能夠爲 __metaclass__ 設置一個type類的派生類,從而查看 類 建立的過程。

 1 class MyType(type):
 2     def __init__(self, class_name, class_bases, class_dic):
 3         if not class_name.istitle():
 4             raise TypeError("類名首字母必須爲大寫")
 5         super(MyType, self).__init__(class_name, class_bases, class_dic)
 6 
 7 
 8     def __call__(self,*args,**kwargs):
 9         obj = self.__new__(self,*args,**kwargs)  # 這裏就是爲何建立類是先執行__new__,再執行__init__的緣由
10         self.__init__(obj,*args,**kwargs)
11         return obj
12 
13 
14 class Foo(metaclass=MyType):
15 
16     def __init__(self, name, age):
17         self.age = age
18         self.name = name
19 
20 
21 f = Foo("tom",18)
22 print(f)  # <__main__.Foo object at 0x054F8E30>
23 print(f.__dict__)  # {'age': 18, 'name': 'tom'}
24 print(Foo.__dict__)  # {'__module__': '__main__', '__init__': <function Foo.__init__ at 0x058D06A8>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}
25 print(Foo.__bases__)  # (<class 'object'>,)
26 
27 print("############################################################")
28 def test(self,name,age):
29     self.name = name
30     self.age = age
31 
32 G = MyType("Goo",tuple(),{"__init__":test})  # <__main__.Foo object at 0x057B85D0>
33 print(G)  # <class '__main__.Goo'>
34 print(G.__dict__)  # {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Goo' objects>, '__weakref__': <attribute '__weakref__' of 'Goo' objects>, '__doc__': None}
35 g = G(name="tom",age=18)
36 print(g.__dict__)  # {'name': 'tom', 'age': 18}
37 print(G.__bases__)  # (<class 'object'>,)
38 
39 
40 # 結論
41 """
42 一、自定義的類Foo是類type的實例化對象
43 二、實例化類Foo,即Foo(*args,**kwargs),則觸發類type的__call__方法
44 三、type的__call__方法裏,可看出來爲何實例化類Foo時先執行__new__再執行__init__
45 ####
46 四、使用type(cls_name,cls_bases,cls_dict)建立類時,cls_dict裏所有是類屬性/方法
47 五、就算cls_bases是空的tuple,該類都是以object爲基類的類
48 """
實測
# 結論
"""
一、自定義的類Foo是類type的實例化對象
二、實例化類Foo,即Foo(*args,**kwargs),則觸發類type的__call__方法
三、type的__call__方法裏,可看出來爲何實例化類Foo時先執行__new__再執行__init__
####
四、使用type(cls_name,cls_bases,cls_dict)建立類時,cls_dict裏所有是類屬性/方法
五、就算cls_bases是空的tuple,該類都是以object爲基類的類
"""

 

元類建立類的過程:

#步驟一:若是說People=type(類名,類的父類們,類的名稱空間),那麼咱們定義元類以下,來控制類的建立
class Mymeta(type):  # 繼承默認元類的一堆屬性
    def __init__(self, class_name, class_bases, class_dic):
        if '__doc__' not in class_dic or not class_dic.get('__doc__').strip():
            raise TypeError('必須爲類指定文檔註釋')

        if not class_name.istitle():
            raise TypeError('類名首字母必須大寫')

        super(Mymeta, self).__init__(class_name, class_bases, class_dic)


class People(object, metaclass=Mymeta):
    __doc__ = "根據if '__doc__' not in class_dic or not class_dic.get('__doc__').strip(),必須定義__doc__或類的描述doc"
    country = 'China'

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

    def talk(self):
        print('%s is talking' % self.name)
元類的__init__控制類的建立
#步驟二:若是咱們想控制類實例化的行爲,那麼須要先儲備知識__call__方法的使用
class People(object,metaclass=type):
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __call__(self, *args, **kwargs):
        print(self,args,kwargs)


# 調用類People,並不會出發__call__
obj=People('tom',18)

# 調用對象obj(1,2,3,a=1,b=2,c=3),纔會出發對象的綁定方法obj.__call__(1,2,3,a=1,b=2,c=3)
obj(1,2,3,a=1,b=2,c=3) #打印:<__main__.People object at 0x05483990> (1, 2, 3) {'a': 1, 'b': 2, 'c': 3}

#總結:若是說類People是元類type的實例,那麼在元類type內確定也有一個__call__,會在調用People('egon',18)時觸發執行,而後返回一個初始化好了的對象obj


#步驟三:自定義元類,控制類的調用(即實例化)的過程
class Mymeta(type): #繼承默認元類的一堆屬性
    def __init__(self,class_name,class_bases,class_dic):
        if not class_name.istitle():
            raise TypeError('類名首字母必須大寫')

        super(Mymeta,self).__init__(class_name,class_bases,class_dic)

    def __call__(self, *args, **kwargs):
        #self=People
        print(self,args,kwargs) #<class '__main__.People'> ('tom', 18) {}

        #一、實例化People,產生空對象obj
        obj=object.__new__(self)


        #二、調用People下的函數__init__,初始化obj
        self.__init__(obj,*args,**kwargs)


        #三、返回初始化好了的obj
        return obj

class People(object,metaclass=Mymeta):
    country='China'

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

    def talk(self):
        print('%s is talking' %self.name)



obj=People('tom',18)
print(obj.__dict__) #{'name': 'tom', 'age': 18}





#步驟四:
class Mymeta(type): #繼承默認元類的一堆屬性
    def __init__(self,class_name,class_bases,class_dic):
        if not class_name.istitle():
            raise TypeError('類名首字母必須大寫')

        super(Mymeta,self).__init__(class_name,class_bases,class_dic)

    def __call__(self, *args, **kwargs):
        #self=People
        print(self,args,kwargs) #<class '__main__.People'> ('tom', 18) {}

        #一、調用self,即People下的函數__new__,在該函數內完成:一、產生空對象obj 二、初始化 三、返回obj
        obj=self.__new__(self,*args,**kwargs)

        #二、必定記得返回obj,由於實例化People(...)取得就是__call__的返回值
        return obj

class People(object,metaclass=Mymeta):
    country='China'

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

    def talk(self):
        print('%s is talking' %self.name)


    def __new__(cls, *args, **kwargs):
        obj=object.__new__(cls)
        cls.__init__(obj,*args,**kwargs)
        return obj


obj=People('tom',18)
print(obj.__dict__) #{'name': 'tom', 'age': 18}
元類的__call__,結合類的__new__,控制類的建立行爲
#步驟五:基於元類實現單例模式
# 單例:即單個實例,指的是同一個類實例化屢次的結果指向同一個對象,用於節省內存空間
# 若是咱們從配置文件中讀取配置來進行實例化,在配置相同的狀況下,就不必重複產生對象浪費內存了
#py文件內容以下
HOST='1.1.1.1'
PORT=3306

#方式一:定義一個類方法實現單例模式


class Mysql:
    __instance=None
    def __init__(self,host,port):
        self.host=host
        self.port=port

    @classmethod
    def singleton(cls):
        if not cls.__instance:
            cls.__instance=cls(HOST,PORT)
        return cls.__instance


obj1=Mysql('1.1.1.2',3306)
obj2=Mysql('1.1.1.3',3307)
print(obj1 is obj2) #False

obj3=Mysql.singleton()
obj4=Mysql.singleton()
print(obj3 is obj4) #True



#方式二:定製元類實現單例模式

class Mymeta(type):
    def __init__(self,name,bases,dic): #定義類Mysql時就觸發

        # 事先先從配置文件中取配置來造一個Mysql的實例出來
        self.__instance = object.__new__(self)  # 產生對象
        self.__init__(self.__instance, HOST, PORT)  # 初始化對象
        # 上述兩步能夠合成下面一步
        # self.__instance=super().__call__(*args,**kwargs)


        super().__init__(name,bases,dic)

    def __call__(self, *args, **kwargs): #Mysql(...)時觸發
        if args or kwargs: # args或kwargs內有值
            obj=object.__new__(self)
            self.__init__(obj,*args,**kwargs)
            return obj

        return self.__instance




class Mysql(metaclass=Mymeta):
    def __init__(self,host,port):
        self.host=host
        self.port=port



obj1=Mysql() # 沒有傳值則默認從配置文件中讀配置來實例化,全部的實例應該指向一個內存地址
obj2=Mysql()
obj3=Mysql()

print(obj1 is obj2 is obj3)

obj4=Mysql('1.1.1.4',3307)



#方式三:定義一個裝飾器實現單例模式

def singleton(cls): #cls=Mysql
    _instance=cls(HOST,PORT)

    def wrapper(*args,**kwargs):
        if args or kwargs:
            obj=cls(*args,**kwargs)
            return obj
        return _instance

    return wrapper


@singleton # Mysql=singleton(Mysql)
class Mysql:
    def __init__(self,host,port):
        self.host=host
        self.port=port

obj1=Mysql()
obj2=Mysql()
obj3=Mysql()
print(obj1 is obj2 is obj3) #True

obj4=Mysql('1.1.1.3',3307)
obj5=Mysql('1.1.1.4',3308)
print(obj3 is obj4) #False
基於元類實現單例模式

 __new__

class Test(object):
    def __init__(self):
        print("__init__")

    def __new__(cls, *args, **kwargs):
        print("__new__")
        res = object.__new__(cls,*args,**kwargs)
        return res

t = Test()

# 實例化前先運行__new__,在__init__
"""
__new__
__init__
"""
__new__ 類實例化時,先運行__new__,再運行__init__

 

class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance


class MyClass(Singleton):
    def __init__(self, name):
            self.name = name

t1 = MyClass("obj1")
t2 = MyClass("obj2")
t3 = MyClass("obj3")
print(id(t1))
print(id(t2))
print(id(t3))

print(t1.name)
print(t2.name)
print(t3.name)

"""
167256688
167256688
167256688
obj3
obj3
obj3
"""
單例模式

 

 

參考or轉發

http://www.cnblogs.com/linhaifeng/articles/6182264.html

http://www.cnblogs.com/linhaifeng/articles/6204014.html

http://www.cnblogs.com/wupeiqi/p/4493506.html

http://www.cnblogs.com/wupeiqi/p/4766801.html

http://www.cnblogs.com/wupeiqi/articles/5017742.html

相關文章
相關標籤/搜索