Python object-oriented advanced programming-_slots_

Source: Internet
Author: User

Using _slots_

Under normal circumstances, when you define a class and create an instance of class, you can bind any property and method to the instance, which is the flexibility of dynamic language. Define class First:

class Student (object):     Pass

Then, try binding an attribute to the instance:

>>> s = Student ()'Michael'print  s.namemichael

You can also try binding a method to an instance:

def set_age (self,age):     = age fromimport  methodtype>>> s.set_age = Methodtype (set_age,     s)>>> s.set_age (+)>>> s.age

However, a method bound to one instance does not work for another instance:

>>> S1 =Student ()>>> S1.name ='Jack'>>>S1.name'Jack'>>> S1.set_age (24) Traceback (most recent): File"<pyshell#18>", Line 1,inch<module>S1.set_age (24) Attributeerror:'Student'object has no attribute'Set_age'>>>

To bind a method to all instances, you can bind the method to class:

>>> student.set_age = set_age>>> s1.set_age >>> s1.age 

Typically, the Set_age method above can be directly defined in class, but dynamic binding allows us to dynamically add functionality to class while the program is running, which is difficult to implement in a static language.

But what if you really want to restrict the properties of an instance? Only add the name and age attributes to the student instance.

For the purpose of limiting, Python allows you to define a special _slots_ variable when defining a class to limit the attributes that the class instance can add:

>>classStudent (object):__slots__= ('name',' Age')    >>> s =Student ()>>> S.score = 99Traceback (most recent): File"<pyshell#34>", Line 1,inch<module>S.score= 99Attributeerror:'Student'object has no attribute'score'>>>

Unless __slot__ is also defined in a subclass, the class instance allows the defined property to be itself __slots__ plus the __slot__ of the parent class

Python object-oriented advanced programming-_slots_

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.