
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Dunder or Magic Methods in Python
magic methods that allow us to do some pretty neat tricks in object oriented programming. These methods are identified by a two underscores (__) used as prefix and suffix. As example, function as interceptors that are automatically called when certain conditions are met.
In python __repr__ is a built-in function used to compute the "official" string representation of an object, while __str__ is a built-in function that computes the "informal" string representations of an object.
Example Code
class String: # magic method to initiate object def __init__(self, string): self.string = string # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # print object location print(my_string)
Output
<__main__.String object at 0x000000BF0D411908>
Example Code
class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # print object location print(my_string)
Output
Object: Python
We are trying to add a string to it.
Example Code
class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # concatenate String object and a string print(my_string + ' Program')
Output
TypeError: unsupported operand type(s) for +: 'String' and 'str'
Now add __add__ method to String class
Example Code
class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) def __add__(self, other): return self.string + other # Driver Code if __name__ == '__main__': # object creation my_string = String('Hello') # concatenate String object and a string print(my_string +' Python')
Output
Hello Python
Advertisements