Friday, December 27, 2024
Google search engine
HomeLanguagesSlots in Python

Slots in Python

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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments