Example of using the _ SLOTS _ attribute in Python, and python _ slots _

Source: Internet
Author: User

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 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.