反射是通过字符串方法去映射属性和方法
getattr():获取
setattr():设置
hasattr():判断是否存在
被引用模块
city="beijing"
country="China"
def eat():
print("eat")
class User:
def __init__(self):
print("我是user")
1.getattr()通过字符串与属性一致,获取到属性值,例如输入city,得到结果:beijing
import tool
var=input("var:")
attr=getattr(tool,var)
print(tool.city)
2.setattr():设置属性
import tool
var=input("var:")
def fun():
print("hhh")
setattr(tool,"test",fun)
获取tool.fun(),得到结果:hhh
3.hasattr():判断属性是否存在
print(hasattr(tool,"city")) #True
print(hasattr(tool,"city1")) # False