![](/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.