简体   繁体   English

如何使用班级的__str__进行打印?

[英]How to make print use my class's __str__?

Is there any way to make Python's print use my class's __str__ , when they are contained by other classes? 有没有什么办法让Python的print用我的课的__str__ ,当它们被其他类包含的?

class C(object):
    def __str__(self):
        return 'MyC'

print C() # OK

print [C()] # prints [<__main__.C object at 0x7fb8774e59d0>]

You have to define __repr__ too since you're not directly calling it's __str__ method and that printing lists calls the values' __repr__ method not __str__ . 您还必须定义__repr__因为您没有直接调用它的__str__方法,并且打印列表调用的是值的__repr__方法而不是__str__

class C(object):
    def __str__(self):
        return 'MyC'
    def __repr__(self):
        return self.__str__() # return the same result as the __str__ method

print C() # prints MyC

print [C()] # also prints MyC

Python will print the repr resentation when in a container, as you see. Python会打印在一个容器中的再版 resentation时,如你所见。 You can define the __repr__ instead of __str__ . 您可以定义__repr__而不是__str__ However, that one is intended to produce strings that can be evaluated to get the object back again, if possible. 但是,如果可能的话,该程序旨在产生可以进行评估以再次返回对象的字符串。 So, to handle both of these situations in your case you can do this. 因此,要在您的情况下处理这两种情况,您可以执行此操作。

class C(object):
    def __repr__(self):
        return 'C()'

print( C() )

print( [C()] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM