反射---hasattr、getattr、setattr、delattr

class Foo:
    f = "类的静态变量"
    def  __init__(self,name,age):
        self.name =  name
        self.age = age
    def  say_hi(self):
        print("hi %s"%self.name)

obj = Foo("egon","100")
#检测是否有某属性
print(hasattr(obj,"name"))
print(hasattr(obj,"say_hi"))
#获取某属性
print(getattr(obj,"name"))
#在获取函数属性时,getattr()或得到的是方法的地址,因此运行此函数需要加括号
getattr(obj,"say_hi")()
#添加属性
setattr(obj,"sb","egon")
print(obj.__dict__)
#删除属性
delattr(obj,"sb")
print(obj.__dict__)

 

posted on 2017-11-24 19:36  云烟||成雨  阅读(119)  评论(0编辑  收藏  举报