Let's talk about the difference between the class Add property method and the instance add property and method,
A class-add attribute is added to a class-global attribute (said to be called a static property), and every instantiation of the class later has this property. Adding a method to a class is also true for each instantiation of the class, but it is said to be a dynamic method. However, adding an attribute to the instance, the scope is the instance, is not the same as the class (it is said that this property is called dynamic property).
Instances of the Python class can add properties dynamically. As an example, declare a Class A
>>> class A (object):
... def __init__ (self):
.. print ' A '
Instantiate an A,
A=a ()
Now give a plus a Name property
>>> a.name= ' AAA '
>>> A.name
' AAA '
Now add a method to Class A
>>> def func ():
... print ' func '
>>> A.func=func
>>> A.func
<bound method A.func of <__main__. A Object at 0x7f323dcb8750>>
>>> A.func ()
Func
So what can slots do? Slots can prevent arbitrary addition of an attribute to an instance.
>>> class A (object):
... def __init__ (self):
... print ' func '
... __slots__= (' name ')
When we modify the Name property, name is modified to AAA,
>>> A=a ()
>>> a.name= ' AAA '
>>> A.name
' AAA '
But when we want to add an age attribute dynamically, we get an error.
>>> a.age=16
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror: ' A ' object has no attribute ' age '
But when you want to add a property to the class as follows, the slots cannot be limited.
>>> a.age=3
Here to say, if the subclass inherits the parent class, the parent class has the slots, this slots is in the subclass does not have the function, if wants to use, can only rewrite slots, achieves the desired result.
The Python class 2--class dynamic Add method and slots (GO)