# 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
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__