First, dynamically add properties
1 class Student (object): 2 Pass 3 4 >>> st = Student ()5'Jack'6 > >> st.name7'Jack'
Second, dynamic to add a method to the instance
1>>> fromTypesImportMethodtype2>>>classStudent (object):3 Pass4 5>>>defSet_age (self, age):6Self.age = Age7 8>>> st.set_age = Methodtype (Set_age, ST)#binding a method to an instance9>>> St.set_age (25)Ten>>>St.age One25
Iii. adding methods to classes dynamically
1>>>classStudent (object):2 Pass3 4>>>defSet_score (self, score):5Self.score =score6 7>>> Student.set_score =Set_score8>>> S1 =Student ()9>>> S1.set_score (100)Ten>>>S1.score One100 A>>> s2 =Student () ->>> S2.set_score (50) ->>>S2.score the50
Iv. restricting the properties of an instance __slots__
1>>>classStudent (object):2 __slots__= ('name',' Age')#Define a property name that allows binding pairs with a tuple3 4>>> s =Student ()5>>> S.name ='Jack'6>>> S.age = 207>>> S.score = 1008 Traceback (most recent):9File"<pyshell#53>", Line 1,inch<module>TenS.score = 100 OneAttributeerror:'Student'object has no attribute'score'
__slots__
The defined properties only work on the current class instance and do not work with inherited subclasses:
1 class graduatestudent (Student): 2 ... Pass 3 ... 4 >>> g = graduatestudent ()5 >>> g.score = 9999
Unless it is also defined in a subclass __slots__
, so that the subclass instance allows the defined property to be its own __slots__
plus the parent class's__slots__:
1>>>classgraduatestudent (Student):2 __slots__= ('score', )3 4>>> g =graduatestudent ()5>>> G.score = 1006>>> G.name ='Mike'7>>> G.age = 108>>> G.other ='ABC'9 Traceback (most recent):TenFile"<pyshell#69>", Line 1,inch<module> OneG.other ='ABC' AAttributeerror:'graduatestudent'object has no attribute' Other'
Python object-oriented six dynamic Add method __slots__ limit Dynamic Add method