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
  • 相关阅读:
    智慧城市建设中政府网站群建设起到了积极的作用
    SQLite 入门教程(四)增删改查,有讲究 (转)
    基于H.264的实时网络摄像——Android客户端
    中小型数据存储方案探讨
    SQL的多表操作
    lua中的时间函数
    C++ 输入输出文件流(ifstream&ofstream)
    linux系统下的shell脚本
    makefile的简单写法
    Linux-ubuntu
  • 原文地址:https://www.cnblogs.com/sewen-H/p/13685006.html
Copyright © 2011-2022 走看看