section-engineering-education / engineering-education

“Section's Engineering Education (EngEd) Program is dedicated to offering a unique quality community experience for computer science university students."
Apache License 2.0
363 stars 889 forks source link

Dunder/Magic Methods in Python #1666

Closed rahulbanerjee26 closed 3 years ago

rahulbanerjee26 commented 3 years ago

Be sure to visit our Resources Page for tools, resources, and example articles to go over.

NOTE: We tend to stray away or tend not to publish reviews/comparisons of commercial product offerings.

Proposed title of article

Your title should be descriptive of the article/tutorial. Be Specific. Use keyword research to gain your article higher ranking.
Dunder/Magic Methods in Python

Introduction paragraph(s):

Please write the Introductory paragraph(s), that would be included in your article. We will use this writing snippet to help us assess overall quality before approval. We're looking for the first 2-3 paragraphs of the article that appropriately summarize what your article will be about. Take your time and write the content as you would intend to get it published.
The article will talk about dunder methods like init, len, getitem, etc. Various example functions and classes will be discussed. Dunder methods are names that are preceded and succeeded by double underscores, hence the name under. They are also called magic methods and can help override functionality for built-in functions for custom classes. Implementing dunder methods for classes is a good form of Polymorphism. If you have created a class in Python and used the init function, you have already been using dunder methods.

Consider the case where we have the following class

class point:
    x = 4
    y = 5

p1 = point()
print(p1)

The print statement would print something like <__main__.point object at 0x7fb992998d00>. However, we might want the print statement to display something in the format (4,10). We can achieve this by overriding the __str__ method of our class.

We could also override other methods such as the len, +, [] etc. We will be creating a new class and override multiple of the built-in functions in this article.


Key takeaways:

What are the 3-5 most important things the reader should understand or be able to do after reading this article? Use this area to get your ideas down on the bulk of your article or tutorial.

References:

Please list links to any published content/research that you intend to use to support/guide this article.

Templates to use as guides

ninjaginja commented 3 years ago

good topic @rahulbanerjee26 - approved