hasattr() getattr() setattr()

hasattr(object,name)函数

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

class function_demo(object):
    name = 'demo'
    def run(self):
        return "hello function"
functiondemo = function_demo
res = hasattr(functiondemo,'name')    #True
res = hasattr(functiondemo,'age')       #False
print(res)

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

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

注意:如果返回的事对象的方法,则打印的结果是:方法的内存地址,如果需要运行这个方法,后面需要加上括号。

class function_demo(object):
    name = 'demo'
    def run(self):
        return "hello function"
functiondemo = function_demo()
a = getattr(functiondemo,'name')    #demo
a = getattr(functiondemo,'age',18)  #18
print(a)

setattr(object,name,values)函数

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

class function_demo(object):
    name = 'demo'
    def run(self):
        return "hello function"
functiondemo = function_demo()
res = hasattr(functiondemo,'name')  #True
print(res)
a = setattr(functiondemo,'age',18)  #None
print(a)
res1 = hasattr(functiondemo,'age')  #True
print(res1)
原文地址:https://www.cnblogs.com/wdz1226/p/10596761.html