python-反射

用到的方法

hasattr
getattr
setattr

isinstance
__import__()
importlib

inspect

参考文档

https://www.cnblogs.com/Guido-admirers/p/6206212.html

示例代码

# preview/demo_reflact


# test1/demo1.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time : 2019/8/18 18:25 
# @Author : test 
# @Software: PyCharm

def get_info():
    print("test1 demo1 get_info")
    
    
    
#test2/demo2.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time : 2019/8/18 18:25 
# @Author : test 
# @File : demo2.py 
# @Software: PyCharm


def set_info():
    print("test2 demo2 set_info")





# common.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time : 2019/8/18 16:58 
# @Author : test 
# @File : commons.py 
# @Software: PyCharm


class Index(object):
    PAGE_LIMIT = 6

    def login(self):
        print("这是一个登陆页面!")

    @classmethod
    def logout(cls):
        print("这是一个退出页面!")

    @staticmethod
    def home():
        print("这是网站主页面!")

    @property
    def page_offset(self):
        return "page_offset"


def login1():
    print("这是一个登陆页面1111!")





# main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Time : 2019/8/18 15:59 
# @Author : test 
# @Software: PyCharm


"""
参考文档:
https://www.cnblogs.com/Guido-admirers/p/6206212.html

python的反射,它的核心本质其实就是利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!
"""

# # step1:
# # 动态导入类中的类方法,变量(属性),单独的方法
import commons

print("****************** step1_basic_use **********************")
# i = commons.Index()
# func = getattr(i, "login")
# func = getattr(i, "logout")

# 报错,需要传递参数self  理论上不应该啊, 需要先实例化



index = commons.Index()
func1 = getattr(index, "login", None)
func1()

func11 = getattr(commons, "login1", None)
func11()

func2 = getattr(commons.Index, "logout")
func2()

offset1 = getattr(commons.Index, "page_offset")
# print(offset())  # error, 是属性
print("offset1:", offset1)

offset2 = getattr(commons.Index(), "page_offset")
print("offset2:", offset2)

attr = getattr(commons.Index, "PAGE_LIMIT")
print(attr)

home = getattr(commons.Index, "home")
home()

# #step2:
# #动态导入类中的静态方法,变量
print("****************** step2 **********************")
if hasattr(commons.Index, "home"):
    func = getattr(commons.Index, 'home')
    func()
else:
    print("404")

# step3:
# 动态导入模块
print("****************** step3 **********************")
# inp = input("请输入您想访问方法的相对路径:").strip()
# modules, func = inp.split("/")
# obj = __import__("test1." + modules, fromlist=(True,))
# if hasattr(obj, func):
#     func = getattr(obj, func)
#     func()
# else:
#     print("404")


inp = input("请输入您想访问方法的相对路径:").strip()  # 请输入您想访问方法的相对路径:demo_reflect.test1.demo1/get_info
modules, func = inp.split("/")
print("modules:", modules)
print("func:", func)
obj = __import__(modules, fromlist=(True,))
if hasattr(obj, func):
    func = getattr(obj, func)
    func()
else:
    print("404")

# step4
# importlib
print("****************** step4 **********************")
import importlib

pa1 = importlib.import_module('b.c.c')              # 绝对导入
pa2 = importlib.import_module('.c.c', package='b')  # 相对导入
print(pa1.args)  # 提取变量args
print(pa1.C)     # 提取class C
print(pa1.C.c)   # 提取class C的c方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值