Python instance-determined properties and methods or class binding methods

Source: Internet
Author: User

Binding properties and methods to an instance object:
1. Bind attributes to an instance: first define a student class

#!/usr/bin/pythonclass Student(object):    pass

Then bind the properties:

s = Student()s.name = ‘AAA‘ # 动态给实例绑定一个属性print(s.name)#输出AAA

2, to the instance binding method: First define a method

def add(self,a,b):    self.a = a    self.b = b    return self.a +self.b

Then bind the method:

When Methodtype binds a method to a class instance, each instance has its own point-of-reference area, which does not interfere with each other. Methodtype (method name, instance object)

from types import MethodTypes.add = MethodType(add,s)print(s.add(10,20))#输出30print(s.a)#输出10print(s.b)#输出20

Second, to the class binding method:
Using Methodtype to bind a method to a class is not to write the method directly inside the class, but rather to create a link to an external method in memory, and this link will be copied when the instance is created.
Methodtype (method name, class name)

Student.add = MethodType(add,Student)s2 = Student()print(s2.add(10,60))#输出70

#也可以把函数直接赋给类. xxx

Student.add = adds3 = Student()print(s3.add(10,60))#输出70

Python instance-determined properties and methods or class binding methods

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.