如何使用print()打印类的实例?

2024-04-24 15:12:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学Python的诀窍。当我试图使用print()函数打印类的对象时,会得到如下输出:

<__main__.Foobar instance at 0x7ff2a18c>

是否有方法可以设置及其对象打印行为(或字符串表示)?例如,当我对类对象调用print()时,我希望以某种格式打印其数据成员。如何在Python中实现这一点?

如果您熟悉C++类,可以通过为类添加<强> ^ {CD5>}方法来实现标准<强> ^ {CD4>}/St>。


Tags: 数据对象方法instance函数字符串标准main
3条回答

As Chris Lutz mentioned,这是由类中的__repr__方法定义的。

^{}的文档中:

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

进行以下等级测试:

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "<Test a:%s b:%s>" % (self.a, self.b)

    def __str__(self):
        return "From str method of Test: a is %s, b is %s" % (self.a, self.b)

…它将在Python shell中按以下方式运行:

>>> t = Test(123, 456)
>>> t
<Test a:123 b:456>
>>> print repr(t)
<Test a:123 b:456>
>>> print(t)
From str method of Test: a is 123, b is 456
>>> print(str(t))
From str method of Test: a is 123, b is 456

如果没有定义__str__方法,print(t)(或print(str(t)))将使用__repr__的结果

如果没有定义__repr__方法,则使用默认值,这相当于。。

def __repr__(self):
    return "<%s instance at %s>" % (self.__class__.__name__, id(self))

一种可以应用于任何没有特定格式的类的通用方法可以执行以下操作:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

然后

elem = Element('my_name', 'some_symbol', 3)
print(elem)

产生

__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
>>> class Test:
...     def __repr__(self):
...         return "Test()"
...     def __str__(self):
...         return "member of Test"
... 
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test

__str__方法是在打印时发生的,而__repr__方法是在使用^{}函数(或使用交互式提示查看)时发生的。如果这不是最有效的方法,我很抱歉,因为我还在学习-但它有效。

如果没有给出__str__方法,Python将打印__repr__的结果。如果您定义了__str__,而不是__repr__,Python将使用上面看到的__repr__,但仍然使用__str__进行打印。

相关问题 更多 >