【问题标题】:How to make class instances not look like '<__main__.Animal at 0x1f053e6abc8> [duplicate]如何使类实例看起来不像'<__main__.Animal at 0x1f053e6abc8> [重复]
【发布时间】:2020-10-09 12:48:45
【问题描述】:

假设我有一个类实例列表,当我在 Python 中调用它时,它看起来像这样:

[<__main__.Animal at 0x1f053e6abc8>,
 <__main__.Animal at 0x1f049e3f848>,
 <__main__.Animal at 0x1f0532e8d08>,
 <__main__.Animal at 0x1f053e6a1c8>]

我可以在类内的代码中添加一些东西,使它们看起来像下面这样吗?

[Lion,
 Gorilla,
 Tiger,
 Baboon]

【问题讨论】:

  • 你能分享你的课吗?

标签: python class oop instance instantiation


【解决方案1】:

为您的类实现__repr__ 方法。它应该返回一个字符串。例如,如果您的班级具有“名称”属性,您可以:

def __repr__(self): return self.name

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 2019-12-02
    • 2011-11-15
    • 2018-08-31
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多