Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What are the Magic or Dunder methods in Python?

Vasista Tummala

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 class
class String:
	
	# magic method to initiate object
	def __init__(self, string):
		self.string = string
		
# Driver Code
if __name__ == '__main__':
	
	# object creation
	string1 = String('Hello')

	# print object location
	print(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 class
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
    string1 = String('Hello')

    # print object location
    print(string1)

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring