Python:DataModel
lastmod 2025-04-25created 2020-10-208 edits
Special method names
- 3. Data model — Python 3.10.6 documentation # 3.3. Special method names
- (Translation) Python's Magic Methods | ziwon.github.io
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names.
Things like __new__, __add__ ...
str
slots
- 10. slots Magic
- Stackoverflow - Usage of slots?
- [Recommended] Advanced Python features | GeekNews
- [Original] 14 Advanced Python Features | Edward Li's Blog [^0]
However, for small classes with known attributes, it can become a bottleneck. The dict type wastes a lot of memory. Python cannot allocate a fixed amount of memory at object creation to store all the attributes. So creating a large number of objects wastes a lot of RAM. There is a way to work around this problem. Using __slots__ tells Python not to use the dict type and to allocate memory only for a fixed set of attributes.
class MyClass(object):
__slots__ = ('name', 'class')
def __init__(name, class):
self.name = name
self.class = class
self.set_up()
# ...
enter/exit
See Python:With for details.
See also
Favorite site
Pages that link here