动态绑定属性和方法

python是动态语言,在创建对象之后,可以动态绑定属性和方法

stu1=Student('小秦同学在上学',20)
stu2=Student('梅达',50)
#一个Student类可以创建N多个Student类的实例对象,每个实例对象的属性值可以不同也可以相同
#每个实例对象都开辟了新的内存空间
print(id(stu1))    #1918636216080
print(id(stu2))    #1918636215120
print(id(Student)) #1918630188464

#为stu1动态绑定属性
stu1.gender='男'
print(stu1.name,stu1.age,stu1.gender)#小秦同学在上学 20 男
#print(stu2.gender)#AttributeError 报错,因为stu2没有动态绑定属性
print(stu2.name,stu2.age)#梅达 50

#为stu1动态绑定方法
def show():
    print('为stu1动态绑定方法,定义在类之外被称为函数,在类里面称为方法')

stu1.show=show

stu1.show()
#stu2.show()#AttributeError 报错,因为stu2没有动态绑定该方法

  

原文地址:https://www.cnblogs.com/xiaoqing-ing/p/14991416.html