python hasattr函数_python: hassttr/getattr/setattr方法使用

classfunction_demo(object):__name = 'demo'name= 'ok'

defrun(self):print("hello function")#hasattr

functiondemo=function_demo()#res = hasattr(functiondemo, '__name') #判断对象是否有__name 属性,True#res = hasattr(functiondemo, 'name') #判断对象是否有__name 属性,True#res = hasattr(functiondemo, "run") #判断对象是否有run方法,True#res = hasattr(functiondemo, "age") #判断对象是否有age属性,False#print(res)

#getattr

#print(getattr(functiondemo, 'name', 'bad'))# 获取name属性,存在就打印出来--- ok## print(getattr(functiondemo, '__name'))# 获取__name属性,报错:AttributeError: 'function_demo' object has no attribute '__name'#print(getattr(functiondemo, '__dir__'))# #print(getattr(functiondemo, "run"))# 获取run方法,存在打印出 方法的内存地址--->#getattr(functiondemo, "run")()# hello function#

#try:#getattr(functiondemo, "age")#except Exception as e:#print(e) # 'function_demo' object has no attribute 'age'#

#print(getattr(functiondemo, "age", 18)) #获取不存在的属性,返回一个默认值18

#setattr

#print(hasattr(functiondemo, 'age')) # 判断age属性是否存在,False#print(setattr(functiondemo, 'age', 18)) # 对age属性进行赋值,无返回值#setattr(functiondemo, 'square', lambda x: x*x) # 对square属性定义匿名函数#print(hasattr(functiondemo, 'age')) # 再次判断属性是否存在,True#print(getattr(functiondemo, 'square')(2)) # 得到值4

#setattr(functiondemo, '__age', 18)#print(getattr(functiondemo, '__age')) # 得到结果18

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值