Special (dunder) methods
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
Why can you write a + b, len(x) or print(x) for your own classes? Because Python turns that ordinary syntax into calls of special methods, the ones named with double underscores. Follow a small Coins class line by line as Coins(3) calls __init__, a + b calls __add__ and print(c) calls __repr__, then see what breaks when a special method is missing.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01A class defines __len__(self) to return 3. What does Python call when you write len(box)?
len(box) asks the object for its length by calling the special method __len__ on its class. That is why len() works on any class that defines __len__.
02In coins.py, what does c = a + b run?
For a + b Python calls the left object's __add__ with the right object as its argument: a.__add__(b), strictly type(a).__add__(a, b). Here it returns a new Coins(7).
03After c = a + b in coins.py, what is a.n?
__add__ reads self.n and o.n and builds a brand-new object with Coins(self.n + o.n). It never changes a or b, so a.n is still 3.
04A class has neither __str__ nor __repr__. What does print() show for one of its objects?
Every class inherits a default __repr__ from object: the module and class name plus a memory address. print() still works; it just is not very readable.
05Coins has no __add__. What happens at c = a + b ?
a + b needs type(a).__add__. Without it Python raises TypeError and stops at that line. (A __radd__ would not help here: Python only tries it when the two operands are of different types.)
المسرد
- Special method
- A method with a reserved name such as __init__ or __add__ that Python calls for you when you use ordinary syntax: Coins(3), a + b, len(x), print(x).
- Dunder
- Short for "double underscore": the two underscores on each side of a special method's name, as in __init__ (said "dunder init").
- __init__
- The special method that sets up a new object. Coins(3) makes the object, then calls __init__ with it as self and 3 as n.
- Attribute
- A name stored inside an object, such as n in self.n = n. Each object keeps its own attributes.
- __add__
- The special method behind +. a + b calls a.__add__(b); it should return the result, usually a new object.
- __repr__
- The special method that returns an object's text form for programmers. print() and str() fall back to it when there is no __str__.
- __str__
- The special method for a friendly text form. print(x) and str(x) use it when a class defines it.
- TypeError
- The error Python raises when an operation does not support a type, such as + between two objects with no __add__.
الملاحظات والمصادر
- "Dunder" is short for "double underscore". The Python docs call these special methods; some books call them magic methods. Never invent new __names__ of your own: Python reserves that form for itself.
- Strictly, Python looks the special method up on the class, not on the object: a + b runs type(a).__add__(a, b). If that is missing (or returns NotImplemented) and b is of a different type, Python tries type(b).__radd__(b, a) before raising TypeError. For two Coins, __radd__ is never tried.
- Coins(3) first calls __new__, which makes the empty object, and then __init__, which fills it in. You almost never need to write __new__ yourself.
- print() and str() use __str__ when a class defines one, and fall back to __repr__ otherwise. The >>> prompt always shows __repr__. Without either, every object inherits the <... object at 0x...> form from object.
- The figure shortens the traceback (it leaves out the File line and the ~~^~~ marker) and wraps the long TypeError line to fit its small terminal; the Try it panel shows the full text. $ is the terminal's own prompt.
- Other common special methods: __len__ for len(x), __eq__ for ==, __lt__ for <, __getitem__ for x[i], __iter__ for for-loops, __contains__ for in, and __str__ for a friendlier print().
- Python reference: Data model, special method names
- Python reference: Basic customization (__new__, __init__, __repr__, __str__)
- Python reference: Emulating numeric types (__add__, __radd__)
- Python reference: Special method lookup
- Python reference: Binary arithmetic operations
- Python tutorial: Classes
- Python library: Built-in functions (print, repr, str, len)
- Python glossary: special method
اختبار يتاح بعد الخطوة الأخيرة.