zoukankan      html  css  js  c++  java
  • python: hassttr/getattr/setattr方法使用

    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
  • 相关阅读:
    20 行代码:Serverless 架构下用 Python 轻松搞定图像分类
    Serverless 的内存配置与超时时间
    Serverless 架构与事件规范
    如何用 Serverless 优雅地给网站图片加水印
    修改rpmbuild构建目录的位置
    rpmbuild之构建目录结构解析
    全量编译与增量编译
    c堆排序的实现
    c优先队列的实现
    c栈的实现
  • 原文地址:https://www.cnblogs.com/sewen-H/p/13685006.html
Copyright © 2011-2022 走看看