• 面向对象(六)-反射方法


    反射方法

    反射:不需要直接调用对象的属性或是方法,通过提供需要运行的方法或属性的名字(字符串),直接内存中搜索有没有与之相同的属性或方法,如果存在直接可以运行即可。

    作用:提高代码容错性以及提升开发效率,扩展性很高

    # 需求:定义用户,人能够说话,唱歌,跳舞.... 
    # 根据用户的输入,去调用相应的方法或属性 
    class User: 
          age = 20 
          gender = "男" 
    
          def speak(self): 
                print("会说话") 
    
          def sing(self): 
                print("唱歌") 
    
          def dancing(self): 
                print("跳舞") 
    
    zs = User() 
    method = input("请输入您要调用的方法:")
     #如何区分属性还是方法? 
    if hasattr(zs,method): 
          method = getattr(zs,method) 
          if callable(method): # 判定对象是否可被调用 
                method() # 调用方法 
          else:
                print(method) # 打印属性 
    else:
          print("输入有误")
    

    ** 常用反射方法 **

    1 hasattr(obj,name_str) :判断object对象是否具有name_str属性或是方法,返回布尔值

    if hasattr(zs,choice): 
          choice = getattr(zs,choice) 
          choice() 
    else:print("输入有误")
    

    2 getattr(obj,name_str):获取object对象中与name_str同名的方法或者函数

    if hasattr(zs,choice): 
          choice = getattr(zs,choice) 
          choice() 
    else:
          print("输入有误")
    

    3 setattr(obj,name_str,value):为object对象设置一个以name_str为名的value方法或者属性

    def wrong(): 
          print("输入有误") 
    if hasattr(zs,choice): 
          choice = getattr(zs,choice) 
          choice() 
    else:
          # 设置属性或方法 
          setattr(zs,choice,wrong)
          # 获取属性或方法 
          getattr(zs,choice)()
    

    4 delattr(obj,name_str):删除object对象中的name_str方法或者属性

    if hasattr(zs,choice): 
          delattr(zs,choice) # 删除实例属性 
          delattr(Person,choice) # 删除实例方法或是类属性 
          if hasattr(zs, choice): 
                print(getattr(zs,choice)) 
          else:
                print(f"没有{choice}属性") 
    else:
          print("输入有误")
    
  • 相关阅读:
    找细胞(题解)
    关于dfs
    奇怪的电梯(题解)
    信息解码(Message Decoding ACM/ICPC 1991)
    查找最大元素
    8皇后问题(dfs)
    如何利用dfs遍历树
    dfs(计算细胞数量)
    决策树减支问题(优化)dfs减支问题
    组合数问题
  • 原文地址:https://www.cnblogs.com/duxiangjie/p/14211518.html
Copyright © 2020-2023  润新知