這篇文章帶給大家的內容是關於Python中hasattr(),getattr(),setattr()的用法介紹(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
1、hasattr(object, name)
# 判斷object裡是否有name屬性,有就回傳True,沒有則回傳False。
class MyClass(object): name = 'jack' age = '22' obj = MyClass() print(hasattr(obj, 'name')) # True print(hasattr(MyClass, 'age')) # True print(hasattr(obj, 'gender')) # False
2. getattr(object, name, [default])
用來取得object的屬性或方法,有就列印出來. 沒有就列印預設值,若是沒有設定預設值則報錯
class MyClass(object): name = 'jack' age = '22' def func(self): return 'hello world!!!' obj = MyClass() print(getattr(MyClass, 'name')) # jack print(getattr(obj, 'age')) # 22 print(getattr(MyClass, 'func')) # <function MyClass.func at 0x000001ACDE9A9AE8> print(getattr(obj, 'func')) # <bound method MyClass.func of <__main__.MyClass object at 0x000001D1505D01D0>> # print(getattr(MyClass, 'func1')) # 没有设置默认值,找不到方法会报错: AttributeError: type object 'MyClass' has no attribute 'func1' print(getattr(MyClass, 'func1', None)) # 设置了默认值None,找不到就会返回默认值: None print(getattr(MyClass, 'func')('self')) # hello world!!! print(getattr(obj, 'func')()) # hello world!!!
3. setattr(object, key, value)
用來對object的屬性key賦值value. 若是key存在,則更新value的值. 若key不存在,則先建立屬性key再對其賦值value.
class MyClass(object): name = 'jack' age = '22' obj = MyClass() setattr(MyClass, 'name', 'tom') print(getattr(MyClass, 'name')) # tom setattr(obj, 'age', 28) print(getattr(obj, 'age')) # 28 setattr(MyClass, 'gender', 'male') print(getattr(MyClass, 'gender')) # male print(getattr(obj, 'gender')) # male setattr(obj, 'hobby', 'skating') print(obj, 'hobby') # <__main__.MyClass object at 0x00000209F5070630> hobby print(MyClass, 'hobby') # <class '__main__.MyClass'> hobby
三個方法一起用:
class MyClass(object): name = 'jack' age = '22' # 判断Myclass是否有gender属性,有则打印,没有则添加 def if_attr(gender='male'): if hasattr(MyClass, 'gender'): return getattr(MyClass, 'gender') return setattr(MyClass, 'gender', gender) if_attr(gender='female') print(getattr(MyClass, 'gender')) # female#
以上是Python中hasattr(),getattr(),setattr()的用法介紹(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!