Class properties for Python-qualified class properties: __slots__

Source: Internet
Author: User

Tag: Cal Call Limit add nbsp Ace Pre Attribute Property

__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 allowed properties for a class: Class Student (object):    __slots__ = (' name ', ' gender ', ' score ')    def __init__ (self, Name, gender, score): = name        Self.gender = gender        Self.score = score Now, operate on the instance:>>> s = Stu Dent (' Bob ', ' Male ', ') >>> = ' Tim ' # ok>>> s.score = # ok>>> s.grade = ' A ' Traceback ( Most recent call last):  ... Attributeerror: ' Student ' object has no attribute ' grade ' __slots__ in order to limit the properties that the current class can have, and if you do not need to add any dynamic properties, using __slots__ can also save memory.

class Person (object):    __slots__ = (' name ', ' Gender ')    def __init__ (self, Name, gender): = name        Self.gender = Genderclass Student (person):    __slots__ = (' score ',)    def __init__ (Self,name,gender,score):        Super (Student,self). __init__ (name,gender)        self.score=scores = Student (' Bob ', ' Male ',) = ' Tim ' S.score = 99print S.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: 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.