from types import MethodType # 声明类时不定义属性和方法 class Student(object): pass # 动态绑定类属性和方法 def set_score(self, score): ... self.score = score Student.set_score = set_score Student.name = 'name' # 动态绑定类实例属性和方法 s.name = 'Michael' s.set_age = MethodType(set_age, s) # 如果要限制实例只能动态添加某些属性,使用__slot__实现,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的 class Student(object): __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
Sign in to make a reply
不息。