Python中类和实例方法、实例属性的动态绑定

it2026-04-08  8

本文转自:https://www.cnblogs.com/zwgblog/p/7235687.html

python中实例创建后可以给实例绑定任何属性和方法

class Student(object): pass

   给实例绑定一个属性:

s=Student() s.name='Michel' print s.name # Michel

   给实例绑定一个方法:

def set_age(self,age): self.age=age from types import MethodType s.set_age=MethodType(set_age,s,Student) s.set_age(25) print s.age #25

   给实例绑定的方法,对另一个实例是不起作用的,为了给所有的实例都绑定方法,可以给class绑定方法

       给类绑定方法

def set_score(self,score): self.score=score Student.set_score=MethodType(set_score,None,Student) s.set_score(100) print s.score #100 s2=Student() s2.set_score(89) print s2.score #89

   上面的set_score方法可以直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能

       __slots__限制class能添加的的属性

class People(object): __slots__=('name','age') #用tuple定义允许绑定的属性名称 p=People() p.name='Michel' p.age=23 p.score=99 #绑定属性score

  由于score没有放到__slots__中,所以不能绑定score属性,此时会报错:AttributeError: 'People' object has no attribute 'score'

  __slots__定义的属性仅对当前的类起作用,对继承的子类是不起作用的,除非在子类中也定义__slots__,这样子类允许定义的属性就是自身的加上父类的

 

class GraduateStudent(Student): pass g=GraduateStudent() g.score=99

 

 参考资料:

转载于:https://www.cnblogs.com/shujuxiong/p/10822659.html

相关资源:python中类和实例如何绑定属性与方法示例详解
最新回复(0)