Python day 9 (1) dynamically bind attributes and methods to the instance, pythonday

Source: Internet
Author: User

Python day 9 (1) dynamically bind attributes and methods to the instance, pythonday

I. The slots method is not used (all added outside the class after the class is defined ):

(1) dynamic attribute binding

class Student(object):

          pass

>>> S = Student () >>> s. name = 'Michael '# dynamically bind an attribute to the instance >>> print (s. name) Michael
(2) dynamic binding method
>>> Def set_age (self, age): # define a function as an instance method... self. age = age... >>> from types import MethodType >>> s. set_age = MethodType (set_age, s) # bind a method to the instance> s. set_age (25) # Call the instance method> s. age # Test Result 25

Note: The method bound to one instance does not work for another instance.
(3) bind methods to all instances (BIND methods to class)
def set_score(self, score):...     self.score = score...>>> Student.set_score = set_score

Ii. Use _ slots _ to restrict instance attributes
For example, the restricted attribute is 'name' and 'age' only'
Class Student (object): _ slots _ = ('name', 'age') # Use tuple to define the names of attributes that can be bound

Use__slots__Note,__slots__The defined attribute only takes effect on the current class instance and does not take effect on the inherited subclass.






 

 

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.