Defined in the class attribute __slot__ attribute field limiting example, in the case of large number of objects can be created to reduce the memory footprint.
The object is to create a large number of memory footprint comparison:
- Class does not use __slot__
class MySlot:def __init__(self, a, b, c): self.a = a self.b = b self.c = c @profile() def main(): myObj_list = list() for i in range(50000): myObj = MySlot(i, i, i) myObj_list.append(myObj)
Results of the:
Line # Mem usage Increment Line Contents
================================================
401 39.7 MiB 39.7 MiB @profile()
402 def main():
403 39.7 MiB 0.0 MiB myObj_list = list()
404 49.9 MiB 0.0 MiB for i in range(50000):
405 49.9 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 49.9 MiB 0.4 MiB myObj_list.append(myObj)
Take up memory about 10M
- Class used __slot__
class MySlot: __slots__ = ('a', 'b', 'c') def __init__(self, a, b, c): self.a = a self.b = b self.c = c @profile() def main(): myObj_list = list() for i in range(50000): myObj = MySlot(i, i, i) myObj_list.append(myObj)
Results of the:
Line # Mem usage Increment Line Contents
================================================
401 40.3 MiB 40.3 MiB @profile()
402 def main():
403 40.3 MiB 0.0 MiB myObj_list = list()
404 45.7 MiB 0.0 MiB for i in range(50000):
405 45.7 MiB 0.1 MiB myObj = MySlot(i, i, i)
406 45.7 MiB 0.3 MiB myObj_list.append(myObj)
Memory for about 5M
- Explanation
__slot__ limit the property value, add attributes other than __slot__ tuple will complain!
__slot__ limitation is to add an instance attribute, a display attribute is not added class!