python学习:实例动态绑定属性和方法

来源:互联网 发布:ubuntu redis 绑定ip 编辑:程序博客网 时间:2024/06/06 12:03

1.动态给实例绑定属性:

class Student(object):passs=Student()s.name='xiaoming'print s.name =====> 输出:xiaoming

2.动态给一个实例绑定方法:----------------------------------》存在问题:只有该实例具有绑定方法,其他实例不能享用

通过导入types的MethodType方法实现

def set_age(self,age):      self.age = ages.set_age(8)   #执行该语句时,系统会报错,因为类中无set_age()方法。
----------------------------------------解决方法-------------------------------------------------------------------------
from types import MethodTypes.set_age = MethodType(set_age,s)s.set_age(25)s.age =======>输出25


3.动态给所有实例绑定方法:--------------------------->通过给class绑定方法实现

def set_score(self,score):     self.score = scoreStudent.set_score = set_score   #类名.方法名=方法名s1 = Student()s1.set_score(100)s1.score ===============================>输出100