zoukankan      html  css  js  c++  java
  • python中反射讲解

    #!/usr/bin/env python 
    # coding: utf-8 -*-
    # 开发团队: 奶豆的小铺
    # 开发人员: bcz
    # 开发时间: 2020/11/26 20:31
    # class Foo():
    #     def __init__(self,name,age):
    #         self.name = name
    #         self.age = age
    #
    #
    #     def show(self):
    #         return '%s-%s'%(self.name,self.age)
    #
    # obj = Foo('alex',23)
    #
    # #第一种方式
    # #__dict__:该方法作用是将对象中封装的所有内容以字典的形式返回
    # b = 'name'
    # print(obj.__dict__)
    # print(obj.__dict__[b])
    #
    #
    # #第二种方式
    # #去什么对象中获取什么内容
    # print(getattr(obj,b))
    #
    # print(getattr(obj,'show'))#获取到的是对象obj中show方法的地址
    #
    # print(getattr(obj,'show')())
    #
    # #判断对象的类中有什么
    # print(hasattr(obj,'name'))
    # print(hasattr(obj,'show'))
    #
    # #设置对象中内容
    # setattr(obj,'k1','v1')
    # print(obj.k1)
    #
    # #删除obj中内容
    # delattr(obj,'k1')
    # print(obj.k1)
    
    
    #getattr setattr hasattr delattr通过字符串的形式操作对象中的成员
    
    #模块也是一个对象,模块的反射也是可以应用的
    # import fanshe
    #
    # print(fanshe.HOBBY)
    # res = getattr(fanshe,'HOBBY')
    # print(res)
    #
    # print(getattr(fanshe,'func')())
    #
    #
    
    
    #反射的应用实例
    
    class Show():
        def f1(self):
            return '首页'
    
        def f2(self):
            return '精选'
    
        def f3(self):
            return '关注'
    
    
    obj = Show()
    
    '''用户输入什么,就看什么'''
    inpt = input('请输入要查看的URL: ')
    
    # res = getattr(fanshe,inpt)
    # print(res())
    if hasattr(obj,inpt):
        res1 = getattr(obj,inpt)
        print(res1())
    
    else:
        print('404')
    
  • 相关阅读:
    数据导入
    数据库导入导出命令
    题库
    struts2的配置文件简洁
    修改oralce11g 字符集为ZHS16GBK
    Linux上安装JDK+Tomcat
    Android中adb的使用
    【转】Android获取IP的方法,并可以判断手机是否联网
    Android中R.java没有自动生成问题
    Android中SQLiteOpenHelper的理解
  • 原文地址:https://www.cnblogs.com/lihuafeng/p/14063808.html
Copyright © 2011-2022 走看看