1. 程式人生 > >Python之面向對象的進階 (3-13)

Python之面向對象的進階 (3-13)

姓名 一次 ttr ini 構造 IT args pri attr

構造方法:在面向對象中,創建一個對象的過程(new一個對象)

技術分享圖片
#new一個對象
# object.__new__()
# class A:
#     def __init__(self):
#         print(‘執行inint方法了‘)
#     def __new__(cls):
#         print(‘執行new方法‘)
#         return object.__new__(cls)  #創造對象並返回
# a=A()
#先執行——new——方法。創造出一個對象
#然後把創造出來的對象傳遞給init方法
#會吧self自動返回,被a接收
new一個對象

元類 創造 類 :所以所有的類的type都是它的元類,默認是type

類 創造 對象:具體創造對象的方法__new__方法,所有的對象的type都是他對應的類

技術分享圖片
class A:#創建一個類
    def __init__(self):pass
    def __new__(cls, *args, **kwargs):#創建一個對象的過程
        return object.__new__(cls)
a=A()
print(type(a))  #》》<class ‘__main__.A‘>
print(type(A))   #》》<class ‘type‘>
元類,類,對象

析構方法:刪除一個對象的時候調用的方法就是析構方法

技術分享圖片
import time
class A:
    def __init__(self):
        self.f=open(log)
    def __del__(self):
        self.f.close()#在刪除之前收尾,關閉文件
        print(刪除一個對象的時候調用)
a=A()
time.sleep(1)
del a #刪除一個對象的時候。如果內部存在——del——方法
        #那麽在刪除一個對象之前。先執行——del——方法
析構方法

單例模式:一個類可以被多次實例化,但是同一時間在Python的內存中,只能有一個實例

運行步驟:

#操作__new__方法,創造一個對象,判斷這個屬性是否在這個類中,如果不在,則使用object.__new__(cls)方法得到類的屬性值。返回這個類的屬性值
# 如果已存在,則直接返回已存在的類的屬性值
技術分享圖片
class A:
    #_instance=None
    def __init__(self,name):
        self.name=name
    def __new__(cls, *args, **kwargs):
        #if not A._instance:
        if not hasattr(cls ,_instance):
            A._instance=object.__new__(cls)
        return A._instance
a1=A(yimi)  #第一次實例化的時候創造一個實例
#a1.name=‘yimi‘
a2=A(titi)
print(a1,a2)    #>>><__main__.A object at 0x00000000021DB390> 
                # >><__main__.A object at 0x00000000021DB390>
print(a1.name,a2.name)   #>>titi titi
單例模式

item系列

包含了增刪改查三種方法:setitem,delitem,getitem

技術分享圖片
class A:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __getitem__(self, item):   #getitem返回一個類中的某個屬性對應的值
        return self.__dict__[item]
    def __setitem__(self, key, value):  #setitem既可以增加也可以做刪除
        self.__dict__[key]=value
    def __delitem__(self, key): #delitem 刪除一個對象的屬性
        del self.__dict__[key]
a=A(yimi,18)
print(a[name])   #>>yimi
print(a[age])   #>>>18
a[sex]=girl
print(a.__dict__)    #>>{‘name‘: ‘yimi‘, ‘age‘: 18, ‘sex‘: ‘girl‘}
del a[sex]
print(a.__dict__)  #》》{‘name‘: ‘yimi‘, ‘age‘: 18}
getitem,setitem,delitem

__call__方法:在對象名後面加(),就是執行類中的__call__方法

技術分享圖片
# class A:
#     def __call__(self):
#         print(‘執行我了‘)
# a=A()()
——call——

hash方法:不可變數據類型都可以被hash

技術分享圖片
class A:
    def __init__(self):
        self.a = 1
        self.b = 2

    def __hash__(self):
        return hash(str(self.a)+str(self.b))
a = A()
print(hash(a))
__hash__方法

技術分享圖片
# 有一個類,對應這個類產生了100個對象
# 每個對象有三個屬性 : 姓名 年齡 性別
# 請對這一百個對象進行去重,如果姓名和性別相同,即便年齡不同也是相同的對象
# 問最簡便的方法?
class Person:#定義一個類
    def __init__(self,name,age,sex):#初始化屬性
        self.name = name#對象的name屬性
        self.age = age#對象的age屬性
        self.sex = sex#對象的sex屬性
    def __hash__(self):#定義哈希方法
        return hash(%s%s%(self.name,self.sex))#返回hash‘self.name,self.sex‘的值
    def __eq__(self, other):#定義一個eq方法
        if self.name == other.name and              self.sex == other.sex:#如果對象屬性等於
            return True
p_lst = []#定義個空列表
for i in range(100):#打印0到99
    p_lst.append(Person(egon,i,male))#p_lst列表添加Person(‘egon‘,i,‘male‘)
p_lst.append(Person(alex,i,male))#p_lst列表添加Person(‘alex‘,i,‘male‘)
p_lst.append(Person(yuan,i,male))#p_lst列表添加Person(‘yuan‘,i,‘male‘)
print(p_lst)
print(set(p_lst)) # 報錯不可hash 完成了__hash__
# hash是否相等   __hash__
# 值是否相等     __eq__

# 收獲1
# 對於一些python當中已經存在的內置函數 內置數據類型 內置模塊中的方法
# 都有可能依賴於類中的內置方法
# 收獲2
# set方法依賴集合中元素對象的__hash__ __eq__
# 金融公司面試題

技術分享圖片
from collections import namedtuple#引用一個collections模塊namedtuple可命名元祖
Card = namedtuple(Card,[rank,suit])#創建一個可命名元祖
# card1 = Card(1,‘紅桃‘)

class FranchDeck:#創建一個類
    ranks = [str(n) for n in range(2,11)] + list(JQKA)#設定大小靜態屬性
    suits = [紅心,方板,梅花,黑桃]#設置花色靜態屬性

    def __init__(self):#初始化一個元祖屬性
        self._cards = [Card(rank,suit) for rank in FranchDeck.ranks
                                        for suit in FranchDeck.suits]

    def __len__(self):#定義一個len方法
        return len(self._cards)# 返回對象的_cards屬性的個數

    def __getitem__(self, item):#查詢方法
        return self._cards[item]#返回一個對象屬性的所有內容

    def __setitem__(self, key, value):
        self._cards[key] = value
deck = FranchDeck()
print(**,deck[:])
from random import choice#引入選擇模塊
print(choice(deck))   # deck對象對應的類中的getitem方法和len方法
from random import shuffle#打亂順序
shuffle(deck)#打印順序
print(**,deck[:])
撲克牌遊戲

Python之面向對象的進階 (3-13)