Python之hasattr()、getattr()和setattr()
1、hasattr(object,attr) 判断一个对象里是否有某个属性或方法,返回布尔值,有为True,否则False
class test():
name = "xiaoxiao"
def say(self):
return "HelloWord"
t = test()
has_name = hasattr(t, ‘name‘)
print(‘是否有name属性:‘, has_name)
运行结果:
运行结果:
是否有name属性:
True
2、getattr(object,attr[,default]) # 获取对象的属性或方法,可设置输出默认值, 如果获取方法,返回的是内存地址,如果需要运行,后面添加一对括号
has_name = getattr(t,‘name‘)
print("name的属性":has_name)
运行结果:name的属性: xiaoxiao
3、setattr(object,attr,values) # 给对象的属性赋值,若属性不存在,则先创建再赋值
p = setattr(t,sex,‘女‘)
print(“sex的属性:”,t.p)
运行结果:sex的属性:女
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16