zoukankan      html  css  js  c++  java
  • python -- 面向对象:反射

    7.6面向对象:反射

    Python面向对象中的反射:通过字符串的形式操作对象相关的属性.Python中的一切事物都是对象(都可以使用反射).

    7.6.1 对 对象的反射

    class Foo:
        a = '类的静态变量'
        
        def __init__(self,name,age):
            self.name = name
            self.age = age
            
        def func(self):
            print(666)
            
    obj = Foo('Agoni',18)
    
    # 检测是否含有某属性
    print(hasatter(obj,'a'))
    print(hasatter(obj,'name'))
    
    # 获取属性
    print(getatter(obj,'age'))
    f = getatter(obj,'func')
    f()
    print(getatter(obj,'sex',None))  # 不存在,返回None,如果没有第三个参数会报错
    
    # 设置属性
    setatter(obj,'hobby','足球')
    print(obj.hobby) # 足球
    
    # 删除属性
    delatter(obj,'name')
    delatter(obj,'job')  # 不存在,会报错
    

    7.6.2 对类的反射

    class Foo:
    	static_field = 'work'
        
        def __init__(self):
            self.name = 'Agoni'
            
        def func(self):
            return 'func'
        
    print(hasatter(Foo,'name'))
    print(getatter(Foo,'static_field'))
    print(getatter(Foo,'func'))
    

    7.6.3 当前模块的反射

    def func():
    	print(111)
    import sys
    this_modules = sys.modules[__name__]   
    print(this_modules)
    print(getatter(this_modules,'func1'))  # 得到func1的内存地址
    
    class A:
        static = 'A类'
        
    import sys
    this_modules = sys.modules[__name__]  # 获取当前脚本这个对象
    cls = getatter(this_modules,'A')      # 获取A类
    obj = cls() # 实例化对象
    print(obj.static)  # A类
    

    7.6.4 其他模块的反射

    #一个模块中的代码  module_test.py
    def test():
        print('from the test')
        
    # 另一个模块中的代码  当前文件
    import module_test as obj
    obj.test()
    print(hasatter(obj,'test'))
    getatter(obj,'test')()
    

    7.6.5 反射的应用***

    class Auth:
        
        def login(self):
            print('登录页面')
            
        def register(self):
            print('注册页面')
            
        def exit(self):
            print('退出...')
           
     while 1:
        obj = Auth()
        choice = input('请输入方法名').strip()
        if hasatter(obj,choice):
            func = getatter(obj,choice)  # choice 必须是个字符串
            func()
        else:
            print('输入错误')
    
  • 相关阅读:
    C++类模板——博客链接
    static成员变量
    C++之++操作符重载
    运算符重载笔记
    纯虚函数(pure virtual function )和抽象类(abstract base class)
    thinkphp 无限极分类的数据库设计及效果测试
    thinkphp 对百度编辑器里的内容进行保存
    thinkphp 最简单的引入百度编辑器的方法
    thinkphp文章列表及删除文章
    thinkphp添加后台的构思以及添加数据功能
  • 原文地址:https://www.cnblogs.com/Agoni-7/p/11197730.html
Copyright © 2011-2022 走看看