Python之反射练习
# 什么是反射?可以用字符串的方式去访问对象的属性 class Test(): _name = "sss" def fun(self): return "Helloword"t = Test()
# print(hasattr(t,"_name")) #hasattr(obj,name)#查看类里面有没有name属性print(hasattr(t,"fun")) #True
if hasattr(t,"_name"):
print(getattr(t,"_name")) #sss
if hasattr(t,"fun"):
print(getattr(t,"fun")()) #Helloword
if not hasattr(t,"age"): #如果属性不存在
print("没有该属性和方法,我来给设置一个")
setattr(t,"age","18") #给t对象设置一个默认值,默认age=18
print(getattr(t,"age"))