Python之反射练习
2020-12-13 16:17
标签:att tool def code blog 字符 logs color cli Python之反射练习 标签:att tool def code blog 字符 logs color cli 原文地址:https://www.cnblogs.com/maaosheng/p/11618784.html
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"))