![](/img/trans.png)
[英]2 threads working on 2 different object instances, but both instances state is changed when one thread change its own instance
[英]Change the object preview into one of its own attributes
怎样把object打印预览改成想要的名字?
class Person:
def __init___(self):
self.name = name
self.age = age
man1 = Person("Jhon",32)
print(man1)
>>> <__main__.Person object at 0x7f9780554b80>
我需要将 object 的预览更改为特定属性。(例如:obj.name,在这个例子中我希望预览将是“Jhon_Person_obj”而不是它的地址)
此代码描述了我需要的打印结果。
print(Jhon_Person_obj)
print(Jhon_Person_obj.age)
>>> <__main__.Personobject at 0x7f9780554bb0>
>>> 32
覆盖 class 的__repr__
方法:
# PEP8: Class names should normally use the CapWords convention.
class Pokemon():
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Pokemon(name='{self.name}')"
用法:
p = Pokemon('Pikachu')
print(p)
# Output
Pokemon(name='Pikachu')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.