How to print instances of a class using print()?

前端 未结 9 1606
南方客
南方客 2020-11-21 07:27

I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I ge

9条回答
  •  天涯浪人
    2020-11-21 07:36

    You need to use __repr__. This is a standard function like __init__. For example:

    class Foobar():
        """This will create Foobar type object."""
    
        def __init__(self):
            print "Foobar object is created."
    
        def __repr__(self):
            return "Type what do you want to see here."
    
    a = Foobar()
    
    print a
    

提交回复
热议问题