วันอังคารที่ 20 กุมภาพันธ์ พ.ศ. 2567

What is the purpose of the __str__ and __repr__ methods in Python classes, and how do they differ in their use cases?

Q6: What is the purpose of the __str__ and __repr__ methods in Python classes, and how do they differ in their use cases?

A6:

  • __str__ Method:

    • The __str__ method is responsible for returning a human-readable string representation of an object.
    • It is invoked when the str() function is used on an object or when the print() function is called with the object as an argument.
    • This method is typically used for displaying information to end-users in a readable format.
    python
    class MyClass: def __str__(self): return "This is an instance of MyClass." obj = MyClass() print(str(obj)) # Output: This is an instance of MyClass.
  • __repr__ Method:

    • The __repr__ method is responsible for returning an unambiguous string representation of an object, primarily for debugging purposes.
    • It is invoked when the repr() function is used on an object or when the backtick notation (``) is used in Python 2 (Note: backticks are not used for repr in Python 3).
    • This method is used by developers to obtain detailed information about an object.
    python
    class MyClass: def __repr__(self): return "MyClass()" obj = MyClass() print(repr(obj)) # Output: MyClass()

In summary, __str__ is for creating a readable representation of an object for end-users, while __repr__ is intended for developers to obtain an unambiguous and detailed representation of an object for debugging and development purposes. 

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be employed to mitigate its effects?

  Q10: How does the Python Global Interpreter Lock (GIL) impact the performance of multi-threaded programs, and what strategies can be emplo...