如何在PYTHON中的class里运用__del__内置方法

时间:2026-02-15 08:42:04

1、class Flower:

    def __init__(self, name):

        self.name = name

        print("This is %s" %self.name)

        

dandelion = Flower("dandelion")

#首先我们定义一个类,这是一个花类,属性是打印花的品名。

如何在PYTHON中的class里运用__del__内置方法

2、class Flower:

    def __init__(self, name):

        self.name = name

        print("This is %s" %self.name)

    def __del__():

        #这里要运用__del,定义的方法类似函数。

如何在PYTHON中的class里运用__del__内置方法

3、class Flower:

    def __init__(self, name):

        self.name = name

        print("This is %s" %self.name)

    def __del__(self):

        #但是务必记得要加上self。

如何在PYTHON中的class里运用__del__内置方法

4、class Flower:

    def __init__(self, name):

        self.name = name

        print("This is %s" %self.name)

    def __del__(self):

        print("The end!")

        

dandelion = Flower("dandelion")      

#设置后再运行一下就会发现最后多了一行,其实就是程序运行的最后会显示__del__的设置。

如何在PYTHON中的class里运用__del__内置方法

5、class Flower:

    def __init__(self, name):

        self.name = name

        print("This is %s" %self.name)

    def __del__(self):

        print("The end of %s" %self.name)

        

dandelion = Flower("dandelion") 

#同样的,__del__也是可以调用属性的。

如何在PYTHON中的class里运用__del__内置方法

6、class Flower:

    def __init__(self, name):

        self.name = name

        print("This is %s" %self.name)

    def __del__(self):

        print("The end of %s" %self.name)

del dandelion

dandelion = Flower("dandelion") 

#从这个语句就可以看出执行的顺序了。

如何在PYTHON中的class里运用__del__内置方法

© 2026 途途旅游
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com