9 魔術方法1

2021-09-27 02:34:11 字數 1339 閱讀 7183

__init__方法有什麼作用?

在建立物件的時候,自動呼叫對建立物件進行初始化設定

__new__方法

__new__方法有什麼用?

建立並返回乙個新的物件,也就是說在建立乙個物件時,會自動觸發這個方法

__init__方法和__new__方法的執行先後順序?

__new__方法是建立並返回個物件

__init__方法是建立物件時,對物件進行初始化

所以,__new__方法在__init__方法前面執行。

並且如果重寫的__new__方法沒有建立物件,那麼__init__方法也不會被呼叫

重寫__new__方法的作用

a.單例模式(最常用)

b.可以在建立物件之前做一些想要做的事情(統計類建立的次數之類的)

c.可以返回自己想要返回的物件

重寫__init__和__new__方法例子

class hero1(object):

def __init__(self, name):

print('執行__init__方法')

self.name = name

h1 = hero1(『hello』)

print(h1.name) # 列印:執行__init__方法 hello

class hero2(object):

def __init__(self, name):

print('執行__init__方法')

self.name = name

def __new__(cls, *args, **kwargs):

print('執行__new__方法')

h2 = hero2() # 列印:執行__new__方法

print(h2) # 因為重寫了__new__方法,沒有建立返回個物件回來。列印:none

class hero3(object):

def __init__(self, name):

print('執行__init__方法')

self.name = name

def __new__(cls, *args, **kwargs):

print('執行__new__方法')

return super().__new__(cls) # 呼叫父類的new方法,建立並返回個物件

h3 = hero3(『hello』)

print(h3) # <main.hero3 object at 0x0000000001df35f8>

print(h3.name) # hello

php的魔術方法1

首先,先了解下什麼是魔術方法?特定情況下能夠自動呼叫的方法,比如熟知的建構函式,析構函式。魔術方法有什麼特徵呢?以雙下劃線開頭,建構函式,析構函式是不是有這個特徵呢?是的。construct destruct php裡還有我們不熟知但常用的方法 get set isset unset 接下來說說他們...

with 魔術方法

with open demo1.py as fp print fp.read enter self exit enter 魔術方法 使用with語句的時候,會呼叫這個魔術方法 這個方法的返回值可以作為as x的值 exit self,exc type,exc val,exc tb 魔術方法 1.執行...

php魔術常量,魔術方法

魔術常量 1。line 返回檔案中的當前行號。2。file 返回檔案的完整路徑和檔名。如果用在包含檔案中,則返回包含檔名。自php4.0.2 起,file 總是包含乙個絕對路徑,而在此之前的版本有時會包含乙個相對路徑。3。function 返回函式名稱 php4.3.0 新加 自php5 起本常量返...