本文透過範例程式碼給大家詳細介紹了Python3 中hasattr()、getattr()、setattr()、delattr()函數,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
hasattr()函數用來判斷是否包含對應的屬性
語法:
hasattr(object,name)
參數:
object--物件
name--字串,屬性名稱
傳回值:
如果物件有該屬性傳回True,否則傳回False
範例:
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) obj=People('aaa') print(hasattr(People,'country')) #返回值:True print('country' in People.__dict__) #返回值:True print(hasattr(obj,'people_info')) #返回值:True print(People.__dict__) ##{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10205d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
getattr(object,name,default)
##name--字串,物件屬性
default--預設回傳值,如果不提供該參數,在沒有對於屬性時,將觸發AttributeError。
傳回值:
傳回物件屬性值
#
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) obj=getattr(People,'country') print(obj) #返回值China #obj=getattr(People,'countryaaaaaa') #print(obj) #报错 # File "/getattr()函数.py", line 32, in <module> # obj=getattr(People,'countryaaaaaa') # AttributeError: type object 'People' has no attribute 'countryaaaaaa' obj=getattr(People,'countryaaaaaa',None) print(obj) #返回值None
setattr函數,用於設定屬性值,該屬性必須存在
語法:
setattr(object,name,value)參數:
object--物件
##name--字串,物件屬性value--屬性值傳回值:無#
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) obj=People('aaa') setattr(People,'x',111) #等同于People.x=111 print(People.x) #obj.age=18 setattr(obj,'age',18) print(obj.__dict__) #{'name': 'aaa', 'age': 18} print(People.__dict__) #{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1007d5620>, 'people_info': <function People.people_info at 0x10215d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'x': 111}
setattr(object,name)
參數:
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) delattr(People,'country') #等同于del People.country print(People.__dict__) {'__module__': '__main__', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10073d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
補充範例:
class Foo: def run(self): while True: cmd=input('cmd>>: ').strip() if hasattr(self,cmd): func=getattr(self,cmd) func() def download(self): print('download....') def upload(self): print('upload...') # obj=Foo() # obj.run()
相關推薦:
python3函式庫numpy陣列屬性的檢視方法
#以上是Python3 中hasattr()、getattr()、setattr()、delattr()函數及範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!