设为首页 加入收藏

TOP

python hasattr() getattr() setattr() 函数使用方法详解
2017-12-11 09:18:45 】 浏览:139
Tags:python hasattr getattr setattr 函数 使用方法 详解

hasattr(object, name) 函数:

判断一个对象里面是否有name属性或者name方法,返回bool值,有name属性返回True,否则返回False。

注意: name要用括号括起来。

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
res = hasattr(functiondemo, 'name')  #判断对象是否有name属性,True

res = hasattr(functiondemo, "run") #判断对象是否有run方法,True

res = hasattr(functiondemo, "age") #判断对象是否有age属性,Falsw
print(res)

 

getattr(object, name[,default]) 函数:

获取对象object的属性或者方法,如果存在则打印出来,如果不存在,打印默认值,默认值可选。

注意:如果返回的是对象的方法,则打印结果是:方法的内存地址,如果需要运行这个方法,可以在后面添加括号()

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
getattr(functiondemo, 'name') #获取name属性,存在就打印出来--- demo 

getattr(functiondemo, "run") #获取run方法,存在打印出 方法的内存地址---<bound method function_demo.run of <__main__.function_demo object at 0x10244f320>>

getattr(functiondemo, "age") #获取不存在的属性,报错如下:
Traceback (most recent call last):
  File "/Users/liuhuiling/Desktop/MT_code/OpAPIDemo/conf/OPCommUtil.py", line 39, in <module>
    res = getattr(functiondemo, "age")
AttributeError: 'function_demo' object has no attribute 'age'

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

 

setattr(object, name,values) 函数:

给对象的属性赋值,若属性不存在,先创建再赋值。

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
res = hasattr(functiondemo, 'age')  # 判断age属性是否存在,False
print(res)

setattr(functiondemo, 'age', 18 )  #对age属性进行赋值,无返回值

res1 = hasattr(functiondemo, 'age') #再次判断属性是否存在,True
print(res1)

 

综合使用:

class function_demo():
    name = 'demo'
    def run(self):
        return "hello function"


functiondemo = function_demo()
res = hasattr(functiondemo, 'addr') # 先判断是否存在
if res:
    addr = getattr(functiondemo, 'addr')
    print(addr)
else:
    addr = getattr(functiondemo, 'addr', setattr(functiondemo, 'addr', '北京首都'))
    #addr = getattr(functiondemo, 'addr', '河南许昌')
    print(addr)

欢迎评论~~~

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇django-admin小试 下一篇单引号 双引号 三个引号 的使用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目