Python 析构方法__del__

class Car:
    def __init__(self):
        print('---ok---')

    def __del__(self):
        print('----deconstrcut-------')


c = Car()
print('31')
del c       #主动触发__del__析构函数,删除实例,会执行__del__里面的代码
print('43')

# 输出结果
# ---ok---
# 31
# ----deconstrcut-------
# 43


# 输出结果
c = Car()
print('31')
print('43')     # 没有主动触发,但程序执行完,对象被销毁,会自动触发,
                # Python的内存回收机制
# 输出结果
# ---ok---
# 31
# 43
# ----deconstrcut-------

猜你喜欢

转载自www.cnblogs.com/wenyule/p/9122198.html
今日推荐