1、构造方法

实例化过程:构造->初始化

构成方法必须要有返回值,返回给初始化方法的self

class A:
    def __init__(self):
        self.x = 1
        print('init')

    def __new__(cls, *args, **kwargs):
        print('new')
        return object.__new__(cls)


a = A()

2、单例模式

关键:构造方法,返回相同的实例对象

class Singleton:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "instance"):
            cls.instance = object.__new__(cls)
        return cls.instance
    

a = Singleton()

b = Singleton()

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2021-04-29
  • 2021-09-01
  • 2022-12-23
  • 2022-12-23
  • 2021-08-11
猜你喜欢
  • 2021-10-02
  • 2021-10-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案