Example of using the _ SLOTS _ attribute in Python, and python _ slots _
Let's see an article about python memory optimization in the daema organization of the python community, using _ slots __. Then I checked it and summarized it. Very useful
When the python class is instantiated, there will be a _ dict _ attribute with available instance attribute names and values. After _ slots _ is declared, the instance will only contain the attribute names in _ slots.
# Coding: UTF-8 class A (object): x = 1 def _ init _ (self): self. y = 2 a = A () print. _ dict _ print (. x,. y). x = 10a. y = 10 print (. x,. y) class B (object): _ slots _ = ('x', 'y') x = 1 z = 2 def _ init _ (self ): self. y = 3 # self. m = 5 # This is unsuccessful B = B () # print (B. _ dict _) print (B. x, B. z, B. y) # B. x = 10 # B. z = 10b. y = 10 print (B. y) class C (object): _ slots _ = ('x', 'z') x = 1 def _ setattr _ (self, name, val ): if name in C. _ slots __: object. _ setattr _ (self, name, val) def _ getattr _ (self, name): return "Value of % s" % name c = C () print (c. _ dict _) print (c. x) print (c. y) # c. x = 10c. z = 10c. y = 10 print (c. z, c. y) c. z = 100 print (c. z)
{'y': 2}(1, 2)(10, 10)(1, 2, 3)10Value of __dict__1Value of y(10, 'Value of y')100