📅  最后修改于: 2023-12-03 15:30:34.855000             🧑  作者: Mango
Dunder Python, also known as "Double Underscore" or "Magic Methods", refers to a set of special methods in Python that begin and end with double underscores. These methods allow developers to define how objects of a class behave in various scenarios, such as arithmetic operations, comparisons, and string representations.
Here are some of the most commonly used dunder methods in Python:
__init__(self[, args...])
: Constructor method that is called when an instance of the class is created.
__str__(self)
: Returns a string representation of the object.
__eq__(self, other)
: Determines if two objects are equal.
__lt__(self, other)
: Determines if one object is less than another.
__add__(self, other)
: Performs addition between two objects.
__len__(self)
: Returns the length of the object.
__getitem__(self, key)
: Returns the value of an item in the object, based on a given key.
__setitem__(self, key, value)
: Sets the value of an item in the object, based on a given key.
Here are some examples of how dunder methods can be used in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age} years old)"
def __eq__(self, other):
return self.name == other.name and self.age == other.age
def __lt__(self, other):
return self.age < other.age
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1)
# Output: Alice (25 years old)
print(person1 == person2)
# Output: False
print(person1 < person2)
# Output: True
In the above example, we define a Person
class with an __init__
method, a __str__
method, an __eq__
method, and an __lt__
method. We then create two instances of the Person
class and demonstrate how these dunder methods can be used to compare and manipulate the objects.
Dunder Python provides a powerful way for developers to extend the functionality of their classes and objects. By using the built-in dunder methods in Python, you can define how your objects behave in a wide variety of scenarios, making your code more efficient and easier to read.