判斷object裏是否有name屬性,有就返回True,沒有則返回False。code
class MyClass(object): name = 'jack' age = '22' obj = MyClass() print(hasattr(obj, 'name')) # True print(hasattr(MyClass, 'age')) # True print(hasattr(obj, 'gender')) # False
用來獲取object的屬性或方法,有就打印出來. 沒有就打印默認值,如果沒有設置默認值則報錯get
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!!!
用來對object的屬性key賦值value. 如果key存在,則更新value的值. 若key不存在,則先建立屬性key再對其賦值value.io
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
三個方法一塊兒用:function
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