Python重寫類的構造 析構方法

2021-10-23 14:47:36 字數 488 閱讀 3217

python提供了預設的構造/析構方法,在需要時可以對其進行重寫,**如下。

class washer:

# 初始化方法,類似於構造方法

def __init__(self, width, height):

print("執行初始化方法")

self.width = width

self.height = height

# 定義列印例項物件的字串,預設是物件的記憶體位址

def __str__(self):

return "washer width={}, height={}".format(self.width, self.height)

# 刪除物件時執行,類似於析構方法

def __del__(self):

print("執行del方法")

w1 = washer(100, 200)

print(w1)

類建構函式,類析構函式

類建構函式 the class constructor 是乙個特殊的類成員函式,當我們建立這個類的新物件時,會被執行。乙個建構函式將被確定與類名相同的名字,沒有任何返回值,包括void。建構函式對於給某些類成員變數設定初始值非常有用。例子 include using namespace std cl...

類建構函式 析構函式

下面的例項有助於更好地理解建構函式的概念 include using namespace std class line 成員函式定義,包括建構函式 line line void void line setlength double len double line getlength void 程式的...

類中建構函式 析構函式與賦值函式的重寫

類中建構函式 析構函式與賦值函式的重寫 class string string 的析構函式 string string void string的普通建構函式 string string const char str else else 拷貝建構函式 string string const strin...