__str__

When printed instance of a class, the returned string is the address information of the object, such as <__ main __. Student object at 0x109afb310>, very ugly
by defining within the class __str __ (), returns an instance when such a printing nice string, and it is easy to see important example of the internal data

  Defined __str __ ()

    class Student(object):
    
        def __init__(self, name):
            self.name = name
            
        def __str__(self):
            return 'Student object (name: %s)' % self.name
        
    print(Student('Michael'))    #输出:Student object (name: Michael)

 

  Direct input variables

    Student = S ( ' Michael ' ) 
    S     # Output: <. __ main __ Student object at 0x109afb310>, or print does not look good examples

 

  Defined __repr __ ()

  Because direct display instance variable, it calls not __str __ (), but __repr __ ()
  __str __ () and __repr __ () difference
  __str __ () returns the user to see the string
  __repr __ () returns the program developers to see the string that __repr __ () for debugging services

  solution is to re-define a __repr __ (), but usually __str __ () and __repr __ () code is the same
  so there is a lazy writing, that is, __str__ directly assigned __repr__

    class Student(object):
    
        def __init__(self, name):
            self.name = name
            
        def __str__(self):
            return 'Student object (name=%s)' % self.name
            
        __repr__ = __str__    
        
    s = Student('Michael')
    s    #输出:Student object (name: Michael)

 

Guess you like

Origin www.cnblogs.com/shiliye/p/10983522.html