1. 程式人生 > 實用技巧 >一些內建的魔術方法

一些內建的魔術方法

一些內建的魔術方法

_call_ : 物件() 呼叫這個類中的__call__方法

class A:
    def __call__(self, *args, **kwargs):
        print('_________')
obj = A()
print(callable(obj))
obj()
A()() #obj = A() ==>obj()
 __len__  : len(物件) 需要實現這個,類中加__len__方法
class Cls:
    def __init__(self,name):
        self.name = name
        self.students = []
    def len(self):
        return len(self.students)
    def __len__(self):
        return len(self.students)
py22 = Cls('py22期')
py22.students.append('大壯')
py22.students.append('alex')
print(py22.len())
print(len(py22))

---------------------
class Pow:
    def __init__(self,n):
        self.n = n
    def __pow2__(self):
        return self.n ** 2

def pow2(obj):
    return obj.__pow2__()

obj = Pow(10)
print(pow2(obj))

__new:

例項化的時候

先建立一塊物件的空間,有一個指標能指向類 --> new

呼叫init --> init

class A:
    def __new__(cls, *args, **kwargs):
        o = object.__new__(cls)
        print('執行new',o)
        return o
    def __init__(self):
        print('執行init',self)
A() 
# 執行new <__main__.A object at 0x00000000022802C8>
# 執行init <__main__.A object at 0x00000000022802C8>

設計模式 -- 單例模式

# 一個類 從頭到尾 只會建立一次self的空間
class Baby:
    __instance = None  #標識
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance
    def __init__(self,cloth,pants):
        self.cloth = cloth
        self.pants = pants
b1 = Baby('紅毛衣','綠皮褲')
print(b1.cloth)  #紅毛衣
b2 = Baby('白襯衫','黑豹紋')
print(b1.cloth)  #白襯衫
print(b2.cloth)  #白襯衫

_str_:幫助我們在列印\展示物件的時候更直觀的顯示物件內容 %s str() print()

_repr_:repr是str的備胎,同時還和%r和repr有合作關係

class clas:
    def __init__(self):
        self.student = []
    def append(self,name):
        self.student.append(name)
    def __str__(self):
        return str(self.student)
#
py22 = clas()
py22.append('大壯')
print(py22)
print(str(py22))
print('我們py22班 %s'%py22)
print(py22)
py22.append('大壯')
print(py22)
# ['大壯']
# ['大壯']
# 我們py22班 ['大壯']
# ['大壯']
# ['大壯', '大壯']
# 在列印一個物件的時候 呼叫__str__方法
# 在%s拼接一個物件的時候 呼叫__str__方法
# 在str一個物件的時候 呼叫__str__方法
class clas:
    def __init__(self):
        self.student = []
    def append(self,name):
        self.student.append(name)
    def __repr__(self):
        return str(self.student)
    def __str__(self):
        return 'aaa'

py22 = clas()
py22.append('大壯')
print(py22)
print(str(py22))
print('我們py22班 %s'%py22)
print('我們py22班 %r'%py22)
print(repr(py22))
# aaa
# aaa
# 我們py22班 aaa
# 我們py22班 ['大壯']
# ['大壯']

# 當我們列印一個物件 用%s進行字串拼接 或者str(物件)總是呼叫這個物件的__str__方法
# 如果找不到__str__,就呼叫__repr__方法
# __repr__不僅是__str__的替代品,還有自己的功能
# 用%r進行字串拼接 或者用repr(物件)的時候總是呼叫這個物件的__repr__方法