Python入門——類和對象:構造和析構


以下內容來自於網課學習筆記。

使用的環境:

  • Window10+64位操作系統
  • PyCharm+Python3.7

一、構造器

1. init(self[,…])

class Rectangle:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getPeri(self):
        print("周長:" + str((self.x + self.y) * 2))

    def getArea(self):
        print("面積:" + str((self.x * self.y)))
        
rect=Rectangle(2,5)
rect.getPeri()
rect.getArea()


📢📢📢: 函數不能帶返回return ··· :

class Rectangle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        return 10

    def getPeri(self):
        print("周長:" + str((self.x + self.y) * 2))

    def getArea(self):
        print("面積:" + str((self.x * self.y)))
rect=Rectangle(2,5)

2. new(cls[,···])

對象實例化時會調用的第一個方法。
在init函數前調用此方法。

第一個參數:是一個類
其他參數:會傳遞給init方法

返回一個類的對象。

很少會重寫此方法。當繼承一個不可變類型時,但又需要更改時,需要使用new方法。

class CapStr(str):
    def __new__(cls, string):
       string=string.upper()
       return str.__new__(cls,string)

a=CapStr("we are family")
print(a)

WE ARE FAMILY

二、析構器

1. del(self)

當對象即將被銷燬時,就會調用del。

class C:
    def __init__(self):
        print("我是init,我正在被調用····")

    def __del__(self):
        print("我是del,我正在被調用····")


c=C()        #——————————————>我是init,我正在被調用····
c2=c
c3=c2
del c3
del c 
# 此時無對象在指向c       
del c2       #——————————————>我是del,我正在被調用····
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章