魔法方法&單例模式

new

觸發(fā): 類進行實例化時
功能: 控制對象的創(chuàng)建
參數(shù): 至少一個cls(類本身)
返回: 使用cls創(chuàng)建的對象

new與init對比

1 new 觸發(fā)比 init要早
    
2 new  是創(chuàng)建對象的
    init 初始化對象


new和init的參數(shù)問題:
    new 和 init 參數(shù)是同步的,
    接收的參數(shù)個數(shù)和類型都要相同
    可以使用 *args **kwargs

new的注意事項

new如果沒有產生自身對象, 則類內置的所有方法將不會執(zhí)行
    
類被調用的返回值由new產生

new基本用法

class Boat(object):
   def __new__(cls, *args, **kwargs):
      print(cls)

      # 通過object的new方法, 創(chuàng)建對象
      # 傳入cls表示創(chuàng)建哪一個類的對象
      obj = object.__new__(cls)

單例模式

單例模式:
   只創(chuàng)建一個對象, 節(jié)省內存空間
   應用在對象只調用, 不添加成員的情況下
   
思想:
   當前類沒有創(chuàng)建過對象, 就創(chuàng)建一個對象, 保存在類屬性中
   當前類已經(jīng)創(chuàng)建過對象, 就從類屬性中尋找, 返回到類調用處

# 1. 基本寫法
class Sington(object):
   # 保存單例對象的類屬性
   __instance = None
   
   def __new__(cls, *args, **kwargs):
      
      # 如果沒有創(chuàng)建過對象的情況, 就創(chuàng)建對象保存在類屬性中
      if not cls.__instance:
         cls.__instance = object.__new__(cls)
         
      # 如果創(chuàng)建過類對象了, 就返回類屬性
      return cls.__instance

析構方法 __ del__

class LangGou(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    def __del__(self):
        print('析構方法被觸發(fā)')
        return 1
        

# 創(chuàng)建一個對象
lang = LangGou('汪汪')

# 刪除對象的引用
del globals()['lang']
# 在單例模式下, 要把類的私有屬性也要刪除
# 沒有引用指向對象才會觸發(fā)析構方法
del LangGou._LangGou__instance

call

觸發(fā): 調用對象時觸發(fā)
功能: 對象名當做函數(shù)名, call方法體當做函數(shù)體
參數(shù): self....
返回: 隨意

# 1.基本用法
class MyClass(object):
   def __call__(self):
      print(123)
      return 456


obj = MyClass()
obj()

str和repr

觸發(fā): print(obj), str(obj)
功能: 查看對象
參數(shù): self...
返回: str


觸發(fā): repr(obj)
功能: 查看對象
參數(shù): self
返回: str

# __str__ = __repr__
# 沒有實現(xiàn)str方法時, 才會去使用repr
# 只有repr(obj)時, 才會調用repr

repr,str使用

class MyClass1(object):
   def __str__(self):
      return 'MyClass1的str方法'


class MyClass2(object):
   def __repr__(self):
      return 'MyClass2的repr方法'


class MyClass3(object):
   def __str__(self):
      return 'MyClass3的str方法'

   def __repr__(self):
      return 'MyClass3的repr方法'


class MyClass4(object):
   pass

print('=================')
print('obj', obj1)
print('str', str(obj1))
print('repr', repr(obj1))
print('=================')
print('obj', obj2)
print('str', str(obj2))
print('repr', repr(obj2))
print('=================')
print('obj', obj3)
print('str', str(obj3))
print('repr', repr(obj3))
print('=================')
print('obj', obj4)
print('str', str(obj4))
print('repr', repr(obj4))
print('=================')


# 運行結果:
=================
obj MyClass1的str方法
str MyClass1的str方法
repr <__main__.MyClass1 object at 0x000002BDB7FE9550>
=================
obj MyClass2的repr方法
str MyClass2的repr方法
repr MyClass2的repr方法
=================
obj MyClass3的str方法
str MyClass3的str方法
repr MyClass3的repr方法
=================
obj <__main__.MyClass4 object at 0x000002BDB7FE9208>
str <__main__.MyClass4 object at 0x000002BDB7FE9208>
repr <__main__.MyClass4 object at 0x000002BDB7FE9208>
=================

Number系列

觸發(fā): bool(obj), int(obj), float(obj), complex(obj)
功能: 強轉對象
參數(shù): self
返回: bool, int, float, complex


class MyClass(object):
    def __bool__(self):
        return False

    def __int__(self):
        return 123

    def __float__(self):
        return 3.14

    def __complex__(self):
        return 1+1j

obj = MyClass()
print(bool(obj))
print(int(obj))
print(float(obj))
print(complex(obj))


# 運行結果:
False
123
3.14
(1+1j)

add和radd

觸發(fā): 使用對象進行加法運算
功能: 加法運算
參數(shù): 兩個對象參數(shù)
返回: 運算后的值

obj在加號左側會觸發(fā)add(), 
并且把右側的數(shù)字傳入到add內的other參數(shù)內
radd正好相反


class MyClass(object):
    def __add__(self, other):
        return 1 + other

    def __radd__(self, other):
        return 10 + other


obj = MyClass()
obj2 = MyClass()





# other接收2數(shù)字對象, 返回3 (1+2)
res = obj + 2
print(res)


# 首先觸發(fā)add(),
# 1 + other, 返回值為: 1+obj2
# 再觸發(fā)radd()
# 10 + other, 返回值: 10 + 1
res = obj + obj2
print(res)

len

觸發(fā): len(obj)
功能: 檢測指定內容的個數(shù)
參數(shù): self..
返回: int


# len(obj) 返回內部自定義成員個數(shù)
class MyClass(object):
    a = 1
    b = 2
    
    def func1(self):
        pass
        
    def func2(self):
        pass


    def __len__(self):
        # 通過MyClass.__dict__, 取出所有MyClass的所有類屬性
        # 把非雙下劃線的屬性加入list, 返回list長度
        li = [i for i in MyClass.__dict__ if not (i.startswith('__') and i.endswith('__'))]

        return len(li)


obj = MyClass()
print(len(obj))
# print(obj.__len__())
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容