Sunday, 5 April 2020

Dunder or Magic methods in python with example

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:

class Cars:
    def __init__(selfnamemodel):
        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

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...