What are the Dunder/Magic/Special methods in Python? Name a few.
What are the Dunder/Magic/Special methods in Python? Name a few.
Dunder, magic, or special methods in Python are a set of predefined methods that start and end with double underscores, such as __init__
or __str__
. These methods are used to enrich the functionality of custom classes by allowing them to interact seamlessly with Python's built-in behaviors and operations[1][2][3][4][5][6][7][8][9].
The term "dunder" stands for "Double Under (Underscores)" and these methods are not typically called directly by the programmer but are invoked internally by Python in response to certain actions. For example, the __init__
method is called when an object is created, __str__
is used to define how the object should be converted to a string, and __add__
is used to define the behavior of the addition operator +
when applied to objects of the class[1][2][3][4][5][6][7][8][9].
Here are a few commonly used dunder methods in Python:
__init__(self, ...)
: Automatically invoked to initialize a newly created object with default or user-provided values[1][2][3][4][5][6][7][8][9].__str__(self)
: Returns a human-readable string representation of the object, useful for debugging and logging[1][2][3][4][5][6][7][8][9].middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào