繁体   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