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"))

复制代码

 

posted @ 2019-10-02 23:09  呵!小鹿  阅读(118)  评论(0编辑  收藏  举报