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
  • 相关阅读:
    HDU 4165 pills
    POJ 2125 Destroy The Graph
    POJ 2075 Tangled in Cables
    NYOJ Number SequenceProblem F
    PHP Eval研究笔记
    PHP 学习备忘(更新中)
    iOS学习笔记1 版本控制
    PHP全局缓存上栽的坑及其他【反面教材系列】
    iOS学习笔记2 Code Format
    iOS学习笔记4 垃圾回收初涉
  • 原文地址:https://www.cnblogs.com/sewen-H/p/13685006.html
Copyright © 2011-2022 走看看