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

Khác biệt giữa __str__ và __repr__ trong Python

repr() và str() gọi object.__repr__(self) và object.__str__(self). repr = official representation, str = informal representation.

Integer: giống nhau

>>> x = 1
>>> repr(x)
'1'
>>> str(x)
'1'

String: khác nhau

>>> x = "Hello"
>>> repr(x)
"'Hello'"  # Có quotes, escape chars
>>> str(x)
'Hello'    # Chỉ nội dung

repr() có thể eval()

>>> y1 = repr(x)
>>> eval(y1)
'Hello'

>>> y2 = str(x)
>>> eval(y2)
NameError: name 'Hello' is not defined

Tóm tắt

  • repr(): default, unambiguous, dành cho developer, có thể eval()
  • str(): informal, readable, dành cho end-user, không nhất thiết unambiguous