1. 程式人生 > >python的__new__方法和__del__方法

python的__new__方法和__del__方法

垃圾回收 pre you def ron class love you () new

new()方法會在init之前調用

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

>>> a = CapStr(‘i love you‘)
>>> a
‘I LOVE YOU‘
>>> 

del(self)

垃圾回收機制調用del方法:

class C:
    def __init__(self):
        print("__init__方法被調用")
        pass
    def __del__(self):
        print("__del__方法被調用")
        pass
    pass

C()

輸出結果:

__init__方法被調用
__del__方法被調用
>>> 

python的__new__方法和__del__方法