Python object-oriented six dynamic Add method __slots__ limit Dynamic Add method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.