1. 程式人生 > 其它 >記錄---python魔術方法

記錄---python魔術方法

一、__new__;__init__

定義:

__init__(self[, ...]):構造器,當一個例項被建立的時候呼叫的初始化方法

__new__(cls[, ...]): 是在一個物件例項化的時候所呼叫的第一個方法

eg:

class Test(object):
def __init__(self, a, b, c):
# 對‘物件‘做初始化的,__new__物件建立之後執行的
print('-------init------方法')

def __new__(cls, *args, **kwargs):
print('------new方法-------')
obj = super().__new__(cls)
return obj


t = Test(11, 22, 33)
print(t)

eg2---單例模式:

class TestDemo:
# 儲存建立物件的屬性,要定義為私有屬性
__instance = 0

def __new__(cls, *args, **kwargs):
# 判斷類是否建立過物件
if cls.__instance == 0:
# 沒有就建立一個,儲存為__instance
cls.__instance = super().__new__(cls)
# 返回建立好的物件
return cls.__instance

二、__enter__;__exit__

定義:

__enter__(self)

  •  定義當使用 with 語句時的初始化行為
  • __enter__ 的返回值被 with 語句的目標或者 as 後的名字繫結

__exit__(self, exc_type, exc_value, traceback)

  • 定義當一個程式碼塊被執行或者終止後上下文管理器應該做什麼
  • 一般被用來處理異常,清除工作或者做一些程式碼塊執行完畢之後的日常工作

eg:

from requests.sessions import Session

with Session() as s:
s.get('http://www.baidu.com')

class MyOpen:
def __init__(self, filename, mode, encoding='utf-8'):
self.f = open(filename, mode=mode, encoding=encoding)

def __enter__(self):
print('---enter---')
return self.f

def __exit__(self, exc_type, exc_val, exc_tb):
print('-----exit---')
print(exc_type,exc_val,exc_tb)

self.f.close()


with MyOpen('eee.txt', 'w', encoding='utf-8') as f:
f.write('222288888888888')

三、__call__

__call__(self[, args...]):允許一個類的例項像函式一樣被呼叫:x(a, b) 呼叫 x.__call__(a, b)

# 函式是一個可呼叫的物件
def work():
print('----work---')


class Demo:
def __call__(self, *args, **kwargs):
print('----call----')


d = Demo()
print(d)
print(work)
# ==============callable:判斷物件是否可呼叫=============
print(callable(d))
print(callable(work))

# 可呼叫的物件,加() 就會執行物件的__call__方法。
# d() # d.__call__(d)

 附錄:https://www.cnblogs.com/nmb-musen/p/10861536.html