• python之类的反射


    hasattr(obj,name_str) , 判断一个对象obj里是否有对应的name_str字符串的方法
    getattr(obj,name_str), 根据字符串去获取obj对象里的对应的方法的内存地址
    setattr(obj,'y',z), is equivalent to ``x.y = v'' ,修改类中的方法或属性
    delattr  #删除类中的方法或属性

    #Author:Anliu
    
    class File(object):
        def __init__(self,name):
            self.name = name
    
        def open(self):
            print("%s is  opening"%self.name)
    d = File("anliu")
    
    def exe(self):
        print(" This is a exe file..")
    
    inode = "10010"
    
    #若此时需要判断某个方法是否在类中,则
    #方法一:
    #choice = input(">>:").strip()
    #if choice == "open":
    #    d.open()
    #方法二:
    choice = input(">>:").strip()
    #print(hasattr(d,choice))
    if hasattr(d,choice):          #判断choice传递的变量是否在实例化后的对象中
        func = getattr(d,choice)   #获取对象所对应的方法的内存地址
        func()                     #执行对象所对应的方法
    
    #倘若想要将外部普通函数添加到类中,该如何?
    #else:
    #    setattr(d,choice,exe)
    #    print(getattr(d,choice)(d))
    
    #倘若想要给类传递一个属性?
    else:
        setattr(d,choice,inode)    #修改类的属性
        delattr(d, choice)         #删除类方法或者属性
        print(getattr(d,choice))
    
    
    


  • 相关阅读:
    队列与双向队列

    linux nohup, jobs, fg, tail指令 指令前后台切换
    linux shell
    Linux学习笔记四 grep, sed, awk
    面试要求
    jenkins send files or publish
    mysql导入脚本
    第三方接口调用框架
    pdm文件name与comment互相同步
  • 原文地址:https://www.cnblogs.com/anttech/p/12846244.html
Copyright © 2020-2023  润新知