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__
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:
- 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
- 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 thestr()
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})'
- 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 therepr()
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__
.
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.
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.