魔法方法__del
# !/usr/bin/python3# -*- coding: utf-8 -*-
# @Time : 2023/2/15 22:47
# @Author : xiongming
# @File : magic_func.py
# @Desc : 魔法方法
# __new__(cls[,...]
class CapStr(str):
def __new__(cls, string):
string = string.upper()
return super().__new__(cls, string)
# 实例创建前进行了拦截,super().__new__()才创建真正的实例
cs = CapStr("FishC")
print(cs)
# __del__(self) 没有引用的实例销毁方法
class C:
def __init__(self):
print("我来了")
def __del__(self):
print("我走了")
c = C()
del c
class D:
def __init__(self, name):
self.name = name
def __del__(self):
global x
x = self
d = D("小甲鱼")
print(d.name)
print(d)
del d
print(x)
print(x.name)
class E:
def __init__(self, name, func):
self.name = name
self.func = func
def __del__(self):
self.func(self)
# 闭包实现实例引用删除后,还保留引用对象
def outer():
x = 0
def inner(y=None):
nonlocal x
if y:
x = y
else:
return x
return inner
print("----------分隔符-----------")
f = outer()
e = E("小甲鱼", f)
print(e)
print(e.name)
del e
g = f()
print(g)
print(g.name)
页:
[1]