Knowee
Questions
Features
Study Tools

Which method would you override to change the string representation of a custom object? __str____repr____string____reprstr__

Question

Which method would you override to change the string representation of a custom object?

__str__
__repr__
__string__
__reprstr__

🧐 Not the exact question you are looking for?Go ask a question

Solution

In Python, to change the string representation of a custom object, you would override the __str__ or __repr__ method.

Here's how you can do it:

  1. Define your custom class. For example, let's create a class named Person.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  1. To change the string representation of the Person object, you can override the __str__ method. This method should return a string, and it will be used when you try to convert the object into a string using the str() function or when you try to print the object.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f'Person(name={self.name}, age={self.age})'
  1. Similarly, you can override the __repr__ method to change the string representation of the object that will be used when you try to display the object in the console or when you use the repr() function.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f'Person(name={self.name}, age={self.age})'

Note: If you only implement one of these methods, Python will use it as a fallback for the other if needed. However, it's a good practice to implement __repr__ for all your classes, and __str__ when you think it would be useful to have a string version of the object that's different from the __repr__.

This problem has been solved

Similar Questions

Which of these method of class String is used to check whether a given object starts with a particular string literal?

Please choose the correct answer.Leveraging the method of str_replace is absolutely safe.TrueFalse

__________is the token which once initialized doesn’t change through- out the program.Options :constantoperatorvariablestring

(i) Without using string slicing operations, create a function which takes in a string, reverse(string), and returns a new string in the reverse order.

Develop an assembly language program that swaps the values of two strings, which can be of any length.

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.