# 单例类 只能实例化一个对象的类叫做单例类 class A: __ISINSTANCE = None def __new__(cls, *args, **kwargs): if not cls.__ISINSTANCE: cls.__ISINSTANCE = object.__new__(cls) return cls.__ISINSTANCE def __init__(self,name,age): self.name = name self.age = age a1 = A('ss',20) a2 = A('sss',30) print(a1) print(a2) # 这样A类就只能实例化一个对象
class B: def __init__(self,name): self.name = name def __str__(self): return self.name b1 = B('sss') # 这个时候我们打印的结果就是str方法返回的结果 print(b1)
class B: def __init__(self, name): self.name = name def __str__(self): return '___%s' % self.name def __repr__(self): return self.name b1 = B('sss') # 当有str时打印str的结果否则打印repr的结果,repr支持%s 与%r ,当父类没有str或repr时在类链查找 print(b1)