1.1 Use__slots__1.1.1 binding of class methods
Adding methods on an instance
>>> class Student (object):
... pass
...
>>> def set_age (Self, Age): # define the function as an instance method, note that the self parameter
... self.age = age
...
>>> s = Student ()
>>> fromtypes Import Methodtype
>>> s.set_age= Methodtype (set_age, s) # Add method to instance s Set_age
>>> S.set_age (24)
>>> S.age
24
>>> S1 = Student ()
>>> S1.set_age-- Note that other instances cannot be called
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror: ' Student ' object has Noattribute ' Set_age '
binding methods to classes - methods for dynamically increasing classes
>>> Defset_score (self, score):
... self.score = Score
...
>>>student.set_score = Set_score
>>> S.set_score (98)
>>> S.score
98
>>> S1.set_score (100)
>>> S1.score
100
1.1.2 Use__slots__
The action restricts the properties of the instance.
>>> class Student (object):
... __slots__ = (' name ', ' age ') # Restrict property names with tuple
...
>>> s = Student ()
>>> s.name = ' Daidai '
>>> S.name
' Daidai '
>>> S.score = 100
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror: ' Student ' object has Noattribute ' score '
Note __slots__ only works on the current class instance
>>> class Gstudent (Student):
... pass
...
>>> g = gstudent ()
>>> g.score = 98-- subclasses can still be defined
>>> G.score
98
sub-class plus __slots__ You can restrict the property names of both the parent class and the child class
>>> class Gstudent (Student):
... __slots__ = (' score ', ' Grade ')
... pass
...
>>> g = gstudent ()
>>> g.unslot=898
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror: ' Gstudent ' object has Noattribute ' Unslot '
>>> g.name = ' Daidai '
>>> G.name
' Daidai '
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826207
Python advanced programming for objects--using __slots__