简体   繁体   English

解释器中的python类输出

[英]python class output at the interpreter

I have the following python class: 我有以下python类:

class uf_node:
    def __init__(self, Vertex):
        self.vertex = Vertex
        self.rep = Vertex

    def set_rep(self, Rep):
        self.rep = Rep

Now, at the interpreter I do the following: 现在,在解释器中,我执行以下操作:

>>> from uf_node import *
>>> u = uf_node('a')
>>> u
<uf_node.uf_node instance at 0x7f56069ca758>

Can one get better output, perhaps creating something like a 'toString()' function that would automatically be called when you try to print the object? 能否获得更好的输出,也许创建类似“ toString()”的函数,当您尝试打印对象时会自动调用该函数?

The REPL invokes __repr__ function of your class. REPL调用类的__repr__函数。 So, you can override __str__ and __repr__ functions like this 因此,您可以像这样覆盖__str____repr__函数

class uf_node:
    def __init__(self, Vertex):
        self.vertex = Vertex
        self.rep = Vertex

    def set_rep(self, Rep):
        self.rep = Rep

    def __str__(self):
        return "Rep: {}, Vertex: {}".format(self.rep, self.vertex)

    def __repr__(self):
        return "Rep: {}, Vertex: {}".format(self.rep, self.vertex)

With this change, 有了这个改变,

>>> u = uf_node('a')
>>> u
Rep: a, Vertex: a
>>> 

Note: You can read more about the differences between __str__ and __repr__ in this excellent answer 注意:您可以在这个出色的答案中详细了解__str____repr__之间的区别。

You can override the str or repr class methods. 您可以覆盖strrepr类方法。

__str__ handles the conversion to a string while __repr__ is the string representation of your class you could use if your wanted to instanciate it again. __str__处理转换为字符串,而__repr__是您的类的字符串表示形式,如果您想再次实例化它的话。 __repr__ is supposed to return a valid Python expression. __repr__应该返回有效的Python表达式。 Both methods return a string. 这两个方法都返回一个字符串。 You usually call these methods with the string constructor str() (the str class will call the __str__ method) or the repr() function. 通常,您可以使用字符串构造函数str() (str类将调用__str__方法)或repr()函数来调用这些方法。

class uf_node(object):
    def __init__(self, Vertex):
        self.vertex = Vertex
        self.rep = Vertex

    def set_rep(self, Rep):
        self.rep = Rep

    def __str__(self):
        '''Used for string conversion'''
        return 'This node uses vertex %s' % self.vertex

    def __repr__(self):
        '''Used for string representation'''
        return 'uf_node(%s)' % repr(self.vertex)

v = uf_node('a')
print str(v) # -> 'This node used vertex a'
print repr(v) # -> "uf_node('a')

Check the doc here, it is well explained : https://docs.python.org/2/reference/datamodel.html 在这里检查文档,它有很好的解释: https : //docs.python.org/2/reference/datamodel.html

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

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