hasattr() getattr() setattr()
阿新 • • 發佈:2019-03-26
name one 函數 clas 結果 內存地址 get val 方法
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‘) #Trueprint(res) a = setattr(functiondemo,‘age‘,18) #None print(a) res1 = hasattr(functiondemo,‘age‘) #True print(res1)
hasattr() getattr() setattr()