Skip to content
Related Articles

Related Articles

Improve Article

Slots in Python

  • Last Updated : 22 Jun, 2020

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:




# defining the class.
class gfg:
      
    # defining the slots.
    __slots__ =('course', 'price')
      
    def __init__(self):
          
        # initializing the values
        self.course ='DSA Self Paced'
        self.price = 3999
  
# create an object of gfg class
a = gfg()
  
# print the slot
print(a.__slots__)
  
# print the slot variable
print(a.course, a.price)

Output

('course', 'price')
DSA Self Paced 3999

Example 2:






# defining the class.
class gfg:
      
    # defining the slots.
    __slots__ =('course', 'price')
      
    def __init__(self):
          
        # initializing the values
        self.course ='oops'
        self.price = 5999
  
# create an object of gfg class
a = gfg()
  
# print the slot
print(a.__slots__)
  
# print the slot variable
print(a.course, a.price)
  
# change the value of the variable
a.course ='System Design'
  
# print the slot variable
print(a.course, a.price)
  
# change the value of the variable
a.price = 9999
  
# print the slot variable
print(a.course, a.price)

Output

('course', 'price')
oops 5999
System Design 5999
System Design 9999

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up