Class properties for Python-qualified class properties: __slots__

Source: Internet
Author: User

__slots__because Python is a dynamic language, any instance can dynamically add properties at run time. If you want to limit the properties that you add, for example, the student class only allows you to add the 3 properties of name, gender, and score, you can take advantage of a special __slots__ of Python. As the name implies,__slots__ refers to a list of properties allowed by a class:classStudent (object):__slots__= ('name','Gender','score')    def __init__(self, name, gender, score): Self.name=name Self.gender=Gender Self.score=score now, take action on the instance:>>> s = Student ('Bob','male', 59)>>> S.name ='Tim' #OK>>> S.score = 99#OK>>> S.grade ='A'Traceback (most recent): ... Attributeerror:'Student'object has no attribute'Grade'The purpose of __slots__ is to limit the properties that the current class can have, using __slots__ can save memory if you don't need to add any dynamic properties.

classPerson (object):__slots__= ('name','Gender')    def __init__(self, Name, gender): Self.name=name Self.gender=GenderclassStudent (person):__slots__= ('score',)    def __init__(Self,name,gender,score): Super (student,self).__init__(name,gender) Self.score=scores= Student ('Bob','male', 59) S.name='Tim'S.score= 99PrintS.score

Class properties for Python-qualified class properties: __slots__

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.