The python __str__ methods and __repr__

If an instance of a class should become str, it will require a special method __str __ ():

class A(object):
def __init__(self,name,age):
self.name=name
self.age=age

def __str__(self):
return "this is __str__"
def __repr__(self):
return "this is __repr__"

If the class is not str and repr method, a printing object instance will be: <__ main __ A object at 0x0000016D7FB1F9B0.>

If you define print in interactive mode:

>>> a=A('OK',18)
>>> a
this is __repr__
>>> print(a)
this is __str__
>>>

Because Python defined __str __ () and __repr __ () two methods, STR __ __ () for display to the user, while __repr __ () for display to the developer.

If the class has not only define repr str method, print (a) will also print the result repr.

 

Guess you like

Origin www.cnblogs.com/pfeiliu/p/11908033.html