classPerson:def__init__(self, name):print("-----------init------------")def__new__(cls,*args,**kwargs):print("-----------new------------")
result =super().__new__(cls)print(result)return result
p1 = Person("Jim")print(p1)
result:-----------new------------<__main__.Person object at 0x7fcf980ce898>-----------init------------<__main__.Person object at 0x7fcf980ce898>
classTest:def__repr__(self):return"------repr-------"
t = Test()print(t)print(t.__repr__())print(id(t))print(id(t.__repr__()))
result:------repr-------------repr-------28629166030722862918614160
# 直接输出对象时,带有__repr__的会输出__repr__的内容。而只带有__str__的还是默认输出。classTest:...def__str__(self):...return"------str-------"... t = Test()
t
<__main__.Test object at 0x00000252B0454908>classTest:...def__repr__(self):...return"------repr-------"... t = Test()
t
------repr-------
# 同时存在时, print优先__str__的内容。classTest:def__repr__(self):return"------repr-------"def__str__(self):return"------str-------"
t = Test()print(t)
result:------str-------