What are the Magic or Dunder methods in Python?
Dunder or sorcery techniques in Python is the strategy of having two prefix and postfix highlights in the strategy name. Here, Dunder signifies Twofold Under (Highlights), which are normally utilized for administrator over-burdening. Models for wizardry techniques are:
init,add,len,repr,- etc.
The init technique for introduction is summoned with no call, when an occasion of a class is made (similar to constructors in certain other programming languages, like, C++, Java, C#, PHP, etc.) These strategies are the reason why we can add two strings with the ‘+’ administrator and no express pigeonholing.
Below is a straightforward execution of what we’ve discussed so far:
# declare our own string classclass String:# magic method to initiate objectdef __init__(self, string):self.string = string# Driver Codeif __name__ == '__main__':# object creationstring1 = String('Hello')# print object locationprint(string1)
The above code only prints the memory address of the string object. So, in order to adress our item, we should add a repr technique.
This is shown below:
# declare our own string classclass String:# magic method to initiate objectdef __init__(self, string):self.string = string# print our string objectdef __repr__(self):return 'Object: {}'.format(self.string)# Driver Codeif __name__ == '__main__':# object creationstring1 = String('Hello')# print object locationprint(string1)