python-dynamic binding of classes and objects (properties, methods)

Source: Internet
Author: User

    • Dynamic binding
#Coding=utf-8" "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." " fromTypesImportMethodtypeclassStudent (object):PassdefSet_age (self, Age): Self.age= Ageif __name__=='__main__': S=Student () s.name='Michael'  #dynamically binding an attribute to an instanceS.set_age = Methodtype (Set_age, s)#binding a method to an instance    Print(s.name) s.set_age (25)    Print(s.age)#The method that is bound to one instance does not work for another instance:Student.set_age = Methodtype (Set_age, Student)#To bind a method to all instances, you can bind the method to class:S1 =Student () s1.set_age (25)    Print(S1.age)
    • Restricted dynamic binding
#Coding=utf-8" "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." "classStudent (object):#What if we want to restrict the properties of an instance? For example, the name and age attributes are only allowed to be added dynamically on student instances.     __slots__= ('name',' Age')#Define a property name that allows binding by using a tuple    classgraduatestudent (Student):Passif __name__=='__main__': S=Student () s.name='lky'S.age= 25#S.score =    Print(S.name, S.age)#__slots__-defined properties work only on the current class instance and do not work on inherited subclasses, unless __SLOTS__ is also defined in the subclass, so that the subclass instance allows the defined property to be its own __slots__ plus the __slots__ of the parent class. g =graduatestudent () G.score= 100G.name='MCs'G.age= 26Print(G.name, G.age, G.score)

python-dynamic binding of classes and objects (properties, methods)

Related Article

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.