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 dynamic language. Define class First:
>>> class Student (object): ... Pass ...
Then, try binding an attribute to the instance:
>>> s = Student () >>> s.name = ' Michael ' # dynamically binds an attribute to an instance >>> print S.namemichael
You can also try binding a method to an instance:
>>> def set_age (self, Age): # defines a function as an instance method ... Self.age = age...>>> from types import methodtype>>> s.set_age = Methodtype (Set_age, S, Student) # bind to instance One method >>> S.set_age (25) # Call instance method >>> S.age # test Result 25
However, the method that is bound to one instance does not work for another instance:
>>> s2 = Student () # Create a new instance >>> S2.set_age (25) # Try calling method Traceback (most recent calls last): File "
", line 1, in
attributeerror: ' Student ' object has no attribute ' set_age '
To bind a method to all instances, you can bind the method to class:
>>> def set_score (self, score): ... Self.score = score...>>> Student.set_score = Methodtype (Set_score, None, Student)
When you bind a method to a class, all instances are callable:
>>> s.set_score >>> s.score100>>> s2.set_score (in) >>> s2.score99
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 a static language.
Using __slots__
But what if we want to restrict the properties of class? For example, only the name and age attributes are allowed on student instances.
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 can add:
>>> class Student (object): ... __slots__ = (' name ', ' age ') # defines the name of the property allowed to bind with a tuple ...
Then, let's try:
>>> s = Student () # Create a new instance >>> s.name = ' Michael ' # Binding property ' name ' >>> s.age = 25 # Binding attribute ' age ' >> > s.score = 99 # binding attribute ' score ' Traceback (most recent call last): File "
", line 1, in
Attribute Error: ' Student ' object has no attribute ' score '
Because ' score ' is not placed in __slots__, the score property cannot be bound, and attempting to bind score will get attributeerror error.
Use __slots__ Note that the properties defined by __slots__ only work for the current class and do not work with inherited subclasses:
>>> class Graduatestudent (Student): ... pass...>>> g = graduatestudent () >>> G.score = 9999Try
Unless __slots__ is also defined in a subclass, the subclass allows the defined property to be its own __slots__ plus the __slots__ of the parent class.