Example python achieve single mode - __new__ single-mode embodiment of the closure function and method of magic

1, single-mode embodiment of the closure function:

# Use single-function closures Example 
DEF SINGLE (CLS, args *, ** kwargs):
    instance = {}

    def get_instance():
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]
    return get_instance


@single
class Apple:
    pass


a = Apple()
b = Apple()
print(id(a))
print(id(b))

2, __new__ single-mode embodiment of the python magic methods:

class Single:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Single, cls).__new__(cls)
        return cls._instance


s1 = Single()
s2 = Single()
print(id(s1))
print(id(s2))

Guess you like

Origin www.cnblogs.com/benben-wu/p/12158397.html