Python/OOP

__str__ vs __repr__

yunajoe 2022. 11. 27. 20:42

__str__ 

 

To customize the string representation of a class instance, the class needs to implement the __str__ magic method.

Internally, Python will call the __str__ method automatically when an instance calls the str() method.

 

class Person:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name 
        self.age= age 
        
    def __str__(self):
        return f'이름: {self.first_name}, 성: {self.last_name}, 나이: {self.age}'
    
    
p1 = Person('yuna', 'Joe', 30)
print(p1)

 

__repr__ 

 

returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object.

When you pass an instance of the Person class to the repr(), Python will call the __repr__ method automatically. For example:

 

 

 

 

 

The main difference between __str__ and __repr__ method is intended audiences.

The __str__ method returns a string representation of an object that is human-readable while the __repr__ method returns a string representation of an object that is machine-readable.

 

 

출처: https://www.pythontutorial.net/python-oop/python-__str__/