谈谈Python动态给实例添加属性和方法

中西医诊疗白癜风 http://m.39.net/news/a_5778433.html
#动态给实例添加属性和方法#-4-18xmjfromtypesimportMethodType#创建一个空类classPerson(object):__slots__=("name","age","speak","height")#可以限制动态添加的属性per=Person()per2=Person()#动态添加属性,这体现了动态语言的特点(灵活)per.name="tom"print(per.name)#动态添加方法defsay(self):print("mynameis"+self.name)per.speak=MethodType(say,per)#给实例绑定一个方法,对另一个实例是不起作用的per.speak()#per2.speak()#AttributeError:speak#为了给所有实例都绑定方法,可以给class绑定方法:defsay2(self,s):print("mynameis"+s)Person.say2=MethodType(say2,Person)#给class绑定方法per.say2("xmj")per2.say2("xmj2")#思考:如果我们想要限制实例的属性怎么办#比如:只允许给对象添加name,age,height,weight属性#解决:定义类的时候,定义一个特殊的属性(__slots__)__slots__=("name","age","speak","height")#可以限制动态添加的属性per.height=print(per.height)预览时标签不可点收录于话题#个上一篇下一篇



转载请注明地址:http://www.sanbaicaoasb.com/sctx/8381.html
  • 上一篇文章:
  • 下一篇文章: 没有了
  • 热点文章

    • 没有热点文章

    推荐文章

    • 没有推荐文章