• python中魔法方法__init__,__str__,__del__的详细使用方法


    1. python中的魔法方法, 类似__init__, __str__等等,这些内置好的特定的方法进行特定的操作时会自动被调用

     

    2. __init__的使用方法

    class 类名(object):
        def __init__(self):
            print("hhahhah")
    对象1 = 类名()

    打印结果:hhahhah

    说明init的方法实例化对象的时候会自动初始化调用

     

    3. __str__的使用方法

    class 类名(object):
        def __str__(self):

    return "hello world"
    对象1 = 类名()
    print(对象1)

    打印结果:hello world

    说明__str__方法会重写原来的方法重写返回自定义的代码

     

    4. __del__的方法使用

    class 类名(object):
        def __del__(self):
            print("%s已经在内存中消失"%self)


    对象1 = 类名()
    del(对象1)
    print("程序最后的代码")

    打印输出:

    __main__.类名 object at 0x000002B9AA1BC160>已经在内存中消失

    程序最后的代码

     

    说明__del__的方法会在创建的对象消失后运行

  • 相关阅读:
    Web Browser使用技巧
    Excel 函数
    删除文件夹, 解决源文件名长度大于文件系统支持的长度问题
    Send Mail using C# code
    动态规划——最长回文子串
    字符串处理总结
    打印日期
    A+B
    对称矩阵
    最小年龄的3个职工
  • 原文地址:https://www.cnblogs.com/valorchang/p/11471159.html
Copyright © 2020-2023  润新知