python gettattr setattr的一个demo
来源:互联网 发布:属于淘宝禁售商品 编辑:程序博客网 时间:2024/06/14 17:35
不多说直接上代码,注释就是说明
class student(): def __init__(self): self.__name = u"123" def __str__(self): return self.__name stu = student()#print getattr(stu,"__name") #报错:student instance has no attribute '__name'print hasattr(stu, u"__name") # False# python的私有变量(__开头)实际上在实例化时自动在名字前加 _类名print hasattr(stu, u"_student__name") # True#添加 __name属性setattr(stu,u"__name",u"456")print getattr(stu,u"__name") # 456print stu # 123setattr(stu,u"_student__name",u"456")print stu # 456def admeth(pstring): # 注意 与types的MethodType不同,setattr添加的函数不需要把self作为第一个参数 print pstringsetattr(stu,u"tt",admeth)stu.tt(u"测试") # 测试#删除 __namedelattr(stu, u"__name")print stu # 456
阅读全文