Python Learning note __7.1 using __slots__

Source: Internet
Author: User
Tags instance method

# This is a learning note for the Liaoche teacher Python tutorial

1 , binding methods for instances

# define a function

>>> def set_age(self, Age): # define a function as an instance method

... self.age = age

# Bind method for instance

>>> from types import Methodtype

>>> s.set_age = methodtype (set_age, s) # Bind a method to an instance

# for Class binding methods

>>> student.set_ Age = set_ Age # Assign a value directly to the class binding method

Attention:

    • A method that binds to an instance that does not work for another instance

    • Dynamic binding allows us to dynamically add functionality to class while the program is running, which is difficult to implement in a static language.

2 , restriction Properties

Python allows you to define a special __slots__ variable when defining a class to limit the properties that the class instance can add

    • Private variables limit our call to properties

    • __slots__ Binding Properties limits Our addition to attributes

Class Student (object):

__slots__ = (' name ', ' age ') # defines the name of the property allowed to bind with a tuple

Note :

    • __slots__ the defined properties only work on the current class instance , it has no effect on inherited subclasses.

    • If __slots__ is also defined in a subclass, A subclass instance allows a defined property to be its own __slots__ plus the parent class's __slots__


Python Learning note __7.1 using __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.