Slots in Python is a special mechanism that is used to reduce memory of the objects. In Python, all the objects use a dynamic dictionary for adding an attribute. Slots is a static type method in this no dynamic dictionary are required for allocating attribute.
Syntax
class myClass(object):
# defining the slots
__slots__ = (par1, par2)
def __init__(self, *args, **kwargs):
# initializing the values
self.par1 = value1
self.par2 = value2
Example 1:
class gfg:
__slots__ = ( 'course' , 'price' )
def __init__( self ):
self .course = 'DSA Self Paced'
self .price = 3999
a = gfg()
print (a.__slots__)
print (a.course, a.price)
|
Output
('course', 'price')
DSA Self Paced 3999
Example 2:
class gfg:
__slots__ = ( 'course' , 'price' )
def __init__( self ):
self .course = 'oops'
self .price = 5999
a = gfg()
print (a.__slots__)
print (a.course, a.price)
a.course = 'System Design'
print (a.course, a.price)
a.price = 9999
print (a.course, a.price)
|
Output
('course', 'price')
oops 5999
System Design 5999
System Design 9999
Last Updated :
22 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...