簡體   English   中英

將object預覽改成自己的屬性之一

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM