Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hàm str() / method __str__ trong Python OOP

Method __str__

__str__ là special method trả về 'informal' string representation của object. Hữu ích cho debugging và hiển thị cho end-user.

Ví dụ

class Time:
    def __init__(self, hour, minute, second=0):
        self.hour = hour
        self.minute = minute
        self.second = second
    
    def __str__(self):
        return '%02d:%02d:%02d' % (self.hour, self.minute, self.second)

t = Time(7, 36)
print(t)  # 07:36:00 - tự động gọi __str__

Kết quả

07:36:00

Lưu ý: Nếu không định nghĩa __str__, Python dùng __repr__ làm fallback.