Blueherb In solitude, where we are least alone

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')
posted @ 2020-11-30 21:19  无敌-蹦蹦  阅读(55)  评论(0编辑  收藏  举报