8th step for python:__new__ && single sample design model

__new__
it give the tmp_space when  a object is instantiation and return it for object,after that the __init__ function will be start as nomal
but need to give the super().__new__(cls) ,
class MusicPlayer:
    def __init__(self):
        print("it is initial")
    def __new__(cls, *args, **kwargs):
        print("space par")
        return super().__new__(cls)
m = MusicPlayer()

single sample design model:
smtimes we just need a class be instantiation to one object ,like the printer machine ,and windows cases controler,so ,we should override the __new__ and __init__ once enough:
class Mus:
    instance = None
    init_flag = False
    def __new__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super().__new__(cls)
        return cls.instance

    def __init__(self):
        if Mus.init_flag :
            return
        else :
            print("init the class")
            Mus.init_flag = True

猜你喜欢

转载自blog.csdn.net/qq_14942375/article/details/80729148
8th