Open In App

Slots in Python

Last Updated : 22 Jun, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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: Python3 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: Python3 1==
# 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

Article Tags :
Practice Tags :

Similar Reads