• 技术文章 >Python技术 >Python基础教程

    python如何解决初始化执行次数

    小妮浅浅小妮浅浅2021-08-27 09:27:43原创3580

    解决方法

    1、定义一个类属性init_flag标记是否 执行过初始化动作,初始值为False。

    2、判断init_flag,False执行初始化。

    然后将 init_flag设置为True。

    3、再次自动调用 __init__ 方法。
    初始化动作就不会被再次执行 了

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    class MusicPlayer(object):

      

        # 记录第一个被创建对象的引用

        instance = None

        # 记录是否执行过初始化动作

        init_flag = False

      

        def __new__(cls, *args, **kwargs):

      

            # 1. 判断类属性是否是空对象

            if cls.instance is None:

                # 2. 调用父类的方法,为第一个对象分配空间

                cls.instance = super().__new__(cls)

      

            # 3. 返回类属性保存的对象引用

            return cls.instance

      

        def __init__(self):

      

            if not MusicPlayer.init_flag:

                print("初始化音乐播放器")

      

                MusicPlayer.init_flag = True

      

      

    # 创建多个对象

    player1 = MusicPlayer()

    print(player1)

      

    player2 = MusicPlayer()

    print(player2)

    以上就是python初始化执行次数的解决,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python初始化
    上一篇:python中__new__的重写 下一篇:python错误类型捕获的方法

    相关文章推荐

    • Python数据可视化库有哪些• Python中Series常用方法整理• Python中OSI七层模型是什么• Python中三种模块类型的介绍• Python继承的原理分析• Python类属性如何使用• python输入数字变成月份• python输入三个数字从小到大排序• python多行注释的方法整理• python列表有哪些特点• python列表数据如何增加和删除• python解释器的多种使用• python字符串的用法总结• python数据结构堆的介绍• python参数调用的注意点• python有哪些注释的种类• python自定义日志如何实现• python如何使用skimage包提取图像• python os.path.join()函数的使用• python confusion_matrix()是什么• python Pandas读取数据文件的优点• python异常中常见关键字

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网