Python | Use of slots (original) (raw)
Last Updated : 27 Dec, 2019
When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary. In case if we need to allocate thousands of objects, it will take a lot of memory space.slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.Example of python object without slots :
Python3 1== `
class GFG(object): def init(self, *args, **kwargs): self.a = 1 self.b = 2
if name == "main": instance = GFG() print(instance.dict)
`
Output :
{'a': 1, 'b': 2}
As every object in Python contains a dynamic dictionary that allows adding attributes. For every instance object, we will have an instance of a dictionary that consumes more space and wastes a lot of RAM. In Python, there is no default functionality to allocate a static amount of memory while creating the object to store all its attributes. Usage of __slots__ reduce the wastage of space and speed up the program by allocating space for a fixed amount of attributes.Example of python object with slots :
Python3 1== `
class GFG(object): slots=['a', 'b'] def init(self, *args, **kwargs): self.a = 1 self.b = 2
if name == "main": instance = GFG() print(instance.slots)
`
Output :
['a', 'b']
Example of python if we use dict :
Python3 1== `
class GFG(object): slots=['a', 'b'] def init(self, *args, **kwargs): self.a = 1 self.b = 2
if name == "main": instance = GFG() print(instance.dict)
`
Output :
AttributeError: 'GFG' object has no attribute 'dict'
This error will be caused.Result of using __slots__:
- Fast access to attributes
- Saves memory space