class function_demo(object):
__name = 'demo'
name = 'ok'
def run(self):
print("hello function")
# hasattr
functiondemo = function_demo()
# res = hasattr(functiondemo, '__name') #判断对象是否有__name 属性,True
# res = hasattr(functiondemo, 'name') #判断对象是否有__name 属性,True
# res = hasattr(functiondemo, "run") #判断对象是否有run方法,True
# res = hasattr(functiondemo, "age") #判断对象是否有age属性,False
# print(res)
# getattr
# print(getattr(functiondemo, 'name', 'bad'))# 获取name属性,存在就打印出来--- ok
# # print(getattr(functiondemo, '__name'))# 获取__name属性,报错:AttributeError: 'function_demo' object has no attribute '__name'
# print(getattr(functiondemo, '__dir__'))# <built-in method __dir__ of function_demo object at 0x0000000001E46A90>
# print(getattr(functiondemo, "run"))# 获取run方法,存在打印出 方法的内存地址---<bound method function_demo.run of <__main__.function_demo object at 0x10244f320>>
# getattr(functiondemo, "run")()# hello function
#
# try:
# getattr(functiondemo, "age")
# except Exception as e:
# print(e) # 'function_demo' object has no attribute 'age'
#
# print(getattr(functiondemo, "age", 18)) #获取不存在的属性,返回一个默认值18
# setattr
# print(hasattr(functiondemo, 'age')) # 判断age属性是否存在,False
# print(setattr(functiondemo, 'age', 18)) # 对age属性进行赋值,无返回值
# setattr(functiondemo, 'square', lambda x: x*x) # 对square属性定义匿名函数
# print(hasattr(functiondemo, 'age')) # 再次判断属性是否存在,True
# print(getattr(functiondemo, 'square')(2)) # 得到值4
# setattr(functiondemo, '__age', 18)
# print(getattr(functiondemo, '__age')) # 得到结果18
python: hassttr/getattr/setattr方法使用
最新推荐文章于 2025-07-24 15:44:52 发布