Printing a list of objects of user defined class

前端 未结 3 547
花落未央
花落未央 2020-11-29 06:14

So I have a class, called Vertex.

class Vertex:
    \'\'\'
    This class is the vertex class. It represents a vertex.
    \'\'\'

    def __in         


        
相关标签:
3条回答
  • 2020-11-29 06:45

    If you want a little more infos in addition of Daniel Roseman answer:

    __repr__ and __str__ are two different things in python. (note, however, that if you have defined only __repr__, a call to class.__str__ will translate into a call to class.__repr__)

    The goal of __repr__ is to be unambiguous. Plus, whenerver possible, you should define repr so that(in your case) eval(repr(instance)) == instance

    On the other hand, the goal of __str__ is to be redeable; so it matter if you have to print the instance on screen (for the user, probably), if you don't need to do it, then do not implement it (and again, if str in not implemented will be called repr)

    Plus, when type things in the Idle interpreter, it automatically calls the repr representation of your object. Or when you print a list, it calls list.__str__ (which is identical to list.__repr__) that calls in his turn the repr representaion of any element the list contains. This explains the behaviour you get and hopefully how to fix it

    0 讨论(0)
  • 2020-11-29 06:58

    If you just want to print the label for each object, you could use a loop or a list comprehension:

    print [vertex.label for vertex in x]
    

    But to answer your original question, you need to define the __repr__ method to get the list output right. It could be something as simple as this:

    def __repr__(self):
        return str(self)
    
    0 讨论(0)
  • 2020-11-29 07:06
    def __ str __ (self):
        return f"Vertex: {self.label} {self.neighbours}"
    
    #In most cases, this is probably the easiest and cleanest way to do it. Not fully sure how this code will interact with your list []. Lastly, any words or commas needed, just add them between the brackets; no further quotes needed.
    
    0 讨论(0)
提交回复
热议问题