Journey to Master Python (WIP)
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Slots for scaling
Python stores all the instant attributes of a class in dict. This is useful to add more run time attributes. However if we create thousands of such instances the impact of it on RAM is very high.
If we know that there are no such instance attributes at runtime then we can create millions of such objects without much impact on RAM. This can be achived by using __slots__
. __slots__
tells python not to use dict but allocate fixed memory for set of attributes.
Slots
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person():
__slots__ = ['name', 'age', 'address']
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
def __str__(self):
return f'Name: {self.name}\nAge: {self.age}\nAddress: {self.address}'
jason = Person('Jason Bourne', '40', 'unknown')
print(jason)
Press desired key combination and then press ENTER.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content