1. 程式人生 > >如何設定顯示內容而不是顯示物件

如何設定顯示內容而不是顯示物件

# coding=utf-8
class Publish():
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    # def __repr__(self):
    #     return "****"
#返回的結果 [****, ****, ****] 會把要顯示的物件給覆蓋掉
#如果沒有 def __repr__ 就會顯示[<__main__.Publish object at 0x013E2770>, <__main__.Publish object at 0x013E2750>, <__main__.Publish object at 0x013E2F90>]
p = Publish("alex") print("2",p) lis = [] for i in range(3): p = Publish("alex"+str(i)) lis.append(p) print(lis) #[<__main__.Publish object at 0x016F2730>, <__main__.Publish object at 0x016F2750>, <__main__.Publish object at 0x016F2F90>] for i in lis: print(i)#物件 alex0 alex1 alex2
print(i.name)#物件的屬性 alex0 alex1 alex2