ฟังก์ชัน built-in str() แปลงออบเจ็กต์ทุกชนิดเป็น String Representation
ตัวอย่าง Built-in Types
>> str(10)
'10'
>>> str(11.11)
'11.11'
>>> str(3 + 4j)
'(3+4j)'
>>> str([1, 2, 3])
'[1, 2, 3]'
>>> str((1, 2, 3))
'(1, 2, 3)'
>>> str({1: 11, 2: 22, 3: 33})
'{1: 11, 2: 22, 3: 33}'
User-defined Class: ต้อง define __str__()
>> class Rectangle:
... def __init__(self):
... self.length = 10
... self.breadth = 10
... def __str__(self):
... return f'length={self.length} breadth={self.breadth}'
>>> r1 = Rectangle()
>>> str(r1)
'length=10 breadth=10' # ใช้ __str__()
# หากไม่มี __str__() จะใช้ __repr__() หรือ default representation
>>> class NoStr:
... pass
>>> str(NoStr())
'<__main__.NoStr object at 0x...>'
ความแตกต่าง str() vs repr()
| ฟังก์ชัน | วัตถุประสงค์ | ผู้ใช้เป้าหมาย |
|---|---|---|
str(obj) | Readable, user-friendly | End users |
repr(obj) | Unambiguous, developer-friendly | Developers/Debugging |
Best Practice: Implement ทั้ง __str__ และ __repr__ ใน Custom Classes