Using in Python

Source: Internet
Author: User
Tags bind instance method in python

This article mainly introduces a detailed tutorial on using the __slots__ method in Python, __slots__ method is an important built-in class method of Python, the code is based on python2.x version, the friend that needs can refer to the

Normally, when we define a class and create an instance of class, we can bind any property and method to that instance, which is the flexibility of the dynamic language. Define class First:

?

1 2 3 >>> class Student (object): ...

Then, try to bind a property to the instance:

?

1 2 3 4 >>> s = Student () >>> s.name = ' Michael ' # dynamically bind a property to an instance >>> print S.name Michael

You can also try to bind a method to an instance:

?

1 2 3 4 5 6 7 8 >>> def set_age (self, Age): # define a function as an instance method ... Self.age = age ... >>> from types import Methodtype >& gt;> s.set_age = Methodtype (Set_age, S, Student) # Bind a method to an instance >>> S.set_age (25) # Invoke instance method >>> S.age # Test Test Results 25

However, the method that is bound to one instance does not work for another instance:

?

1 2 3 4 5 >>> s2 = Student () # Create new instance >>> S2.set_age (25) # Try calling method Traceback (most recent call last): File "<std In> ", line 1, in <module> attributeerror: ' Student ' object has no attribute ' set_age '

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

?

1 2 3 4 >>> def set_score (self, score): ... Self.score = score ... >>> student.set_score = Methodtype (Set_score, None, Student)

After the class is bound to a method, all instances can be invoked:

?

1 2 3 4 5 6 >>> s.set_score >>> s.score >>> s2.set_score ($) >>> S2.score 99

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

Using __slots__

But what if we want to restrict the attributes of class? for example, only add the name and age attributes to the student instance.

To achieve the limit, Python allows you to define a special __slots__ variable when defining class to limit the attributes that class can add:

?

1 2 3 >>> class Student (object): ... __slots__ = (' name ', ' age ') # Use tuple to define property names that allow binding ...

Then, let's try:

?

1 2 3 4 5 6 7 >>> s = Student () # Create new instance >>> S.name = ' Michael ' # binding attribute ' name ' >>> s.age = 25 # Binding attribute ' age ' >& Gt;> s.score = 99 # binding attribute ' score ' traceback (most recent call last): File "<stdin>", line 1, in <module> Attr Ibuteerror: ' Student ' object has no attribute ' score '

Because ' score ' is not placed in the __slots__, the score property cannot be bound, and attempting to bind score will get the Attributeerror error.

Use __slots__ to note that __slots__-defined properties work only for the current class and do not work on inherited subclasses:

?

1 2 3 4 5 6 >>> class Graduatestudent (Student): ... >>> g = graduatestudent () >>> G.score = 9999 T Ry

Unless __slots__ is also defined in subclasses, the subclass allows the defined property to be its own __slots__ plus the __slots__ of the parent class.

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.