# -*- coding: UTF-8 -*- # __init__ 初始化方法 # __new__构造方法:创建一个对象 #设计模式 23 种 #单例模式:1个类 始终只有一个实例 #当第一次实例化这个类的时候,就创建一个实例化对象 #当再来实例化的时候,就用之前创建的对象 from unittest.test.testmock.testpatch import Foo class Foo: __instance = False def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def __new__(cls, *args, **kwargs): #单例模式 if not cls.__instance: cls.__instance = object.__new__(cls) # cls.__instance = object.__new__(cls, *args, **kwargs) #单机模式(有的电脑需要这么写) return cls.__instance nezha = Foo("哪吒",22,'男') print(nezha) nezha.cloth = "棉袄" santaizi = Foo("三太子",30,'男') print(nezha) print(santaizi) print(nezha.name) print(santaizi.name) print(nezha.cloth) print(santaizi.cloth)