Magic methods are usually represented by two underscores at front and two at the back of method names. The name Dunder is because of these underscores. Also mainly used for operator overloading.
In the below example you can see two methods "str" and "repr" with two underscore at the front and two at the back. These two methods are used to give user a output if there are no proper return methods in a class. These can also be used to give a message on the function that has been performed in a class.
Example:
Output:
Ferrari is manufactured in the year 2019
In the below example you can see two methods "str" and "repr" with two underscore at the front and two at the back. These two methods are used to give user a output if there are no proper return methods in a class. These can also be used to give a message on the function that has been performed in a class.
Example:
class Cars:
def __init__(self, name, model):
self.name = name
self.model = model
def __str__(self):
return (f"{self.name} is manufactured in the year {self.model}")
def __repr__(self):
return (f"<{self.name} is manufactured in the year {self.model}/>")
car = Cars("Ferrari", "2019")
print(car)
Output:
Ferrari is manufactured in the year 2019
No comments:
Post a Comment