Skip to content
Search

Python:DataModel

lastmod 2025-04-25created 2020-10-208 edits

Special method names

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

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

author Zer0 sitemap