Zhong__Python反射

时间:2020.12.09

环境:Python3

目的:反射常用的方法使用

说明:

作者:Zhong QQ交流群:121160124 欢迎加入!

 

需求

需要执行或调用对象或函数中的某个方法或变量,但不确定此方法或变量是否存在!例如如下的示例代码:

class Animal():

    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    def info(self):
        print(self.name)
        print(self.weight)

# 实例化一个对象
rabbit = Animal("兔子", 5)

"""
hasattr
    使用hasattr方法查看对象中是否有某个方法或变量
"""

# 查看rabbit对象中是否有name属性(方法或变量)
print(hasattr(rabbit, "name"))  # True
# 查看rabbit对象中是否有info属性(方法或变量)
print(hasattr(rabbit, "info"))  # True
# 查看rabbit对象中是否有behavior属性(方法或变量)
print(hasattr(rabbit, "behavior"))  # False

"""
getattr
    使用getattr方法获取对象中的方法内存地址或变量
"""

# 获取rabbit对象中name属性(方法或变量)
print(getattr(rabbit, "name"))  # name为变量 输出变量值:兔子
# 获取rabbit对象中info属性(方法或变量)
print(getattr(rabbit, "info"))  # info为方法 输出方法描述:<bound method Animal.info of <__main__.Animal object at 0x00000242938A8EB0>>
# 获取rabbit对象中behavior属性(方法或变量)
# print(getattr(rabbit, "behavior"))  # 没有behavior属性 输出属性错误提示:AttributeError: 'Animal' object has no attribute 'behavior'
# 获取rabbit对象中behavior属性(方法或变量)
print(getattr(rabbit, "behavior", "没有此属性"))  # 没有behavior属性 输出自定义提示信息:没有此属性

"""
setattr(不常用)
    使用setattr为对象添加变量或方法
"""

"""
delattr(不常用)
    删除对象中的变量(不能删除对象中的方法)
"""

使用场景

策略管理API,根据前端用户传入的参数action动态调用相应的方法返回结果。如果使用if else等语句判断参数逐个匹配,不但要写很多代码,而且维护也繁琐,此时可以使用python反射借助getattr()方法实现。

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from casbin_middleware.middleware import enforcer
from rbac.models import CasbinRule


class PolicyManagement(APIView):

    def __init__(self):
        super().__init__()
        self.e = enforcer
        self.action = ""

    def get(self, request):
        try:
            username = request.user.username

            args = request.query_params
            self.action = func_name = request.query_params.get("action")

            func = getattr(self, func_name, self.func_not_found)
            res_data = func(args)

            res_data = {
                "username": username,
                "data": res_data
            }
            return Response(data=res_data, status=status.HTTP_200_OK)
        except Exception as e:
            return Response(data=e, status=status.HTTP_400_BAD_REQUEST)

    # get方法中调用 如果没有对应的方法则调用此方法
    def func_not_found(self, *args, **kwargs):  # just in case we dont have the function
        print("没有此方法 " + self.action)
        return "参数error!没有此方法 %s" % self.action

    # 获取当前策略中显示的主题列表
    def GetAllSubjects(self, args, **kwargs):
        res_data = self.e.get_all_subjects()

        return res_data

    # 获取当前命名策略中显示的主题列表
    def GetAllNamedSubjects(self, args, **kwargs):
        res_data = self.e.get_all_named_subjects(ptype=args['ptype'])

        return res_data

    # 获取当前策略中显示的对象列表
    def GetAllObjects(self, args, **kwargs):
        res_data = self.e.get_all_objects()

        return res_data

    # 获取当前命名策略中显示的对象列表
    def GetAllNamedObjects(self, args, **kwargs):
        res_data = self.e.get_all_named_objects(ptype=args['ptype'])

        return res_data

    # 获取当前策略中显示的操作列表
    def GetAllActions(self, args, **kwargs):
        res_data = self.e.get_all_actions()

        return res_data

    # 获取当前命名策略中显示的操作列表
    def GetAllNamedActions(self, args, **kwargs):
        res_data = self.e.get_all_named_actions(ptype=args['ptype'])

        return res_data

    # 获取当前策略中显示的角色列表
    def GetAllRoles(self, args, **kwargs):
        res_data = self.e.get_all_roles()

        return res_data

    # 获取当前命名策略中显示的角色列表
    def GetAllNamedRoles(self, args, **kwargs):
        res_data = self.e.get_all_named_roles(ptype=args['ptype'])

        return res_data

    # 获取策略中的所有授权规则
    def GetPolicy(self, args, **kwargs):
        # res_data = self.e.get_policy()
        objects_all = CasbinRule.objects.all().values("id", "ptype", "casbinrulemap__name")
        for obj in objects_all:
            print(obj)
        res_data = {}

        return res_data

    # 获取策略中的所有授权规则,可以指定字段筛选器
    def GetFilteredPolicy(self, args, **kwargs):
        res_data = self.e.get_filtered_policy(int(args['field_index']), args['name'])

        return res_data

 

 关注微信公众号

 

我下载的代码没有.mat文件,他论文使用的四个数据集,我发给你。1.Pavia University 1. This dataset was acquired by the Reflective Optics System Imaging Spectrometer (ROSIS) on the campus of Pavia University in northern Italy in 2001. It has 103 spectral bands. The dataset consists of 610 by 340 pixels and covers 9 main categories of interest. 帕维亚大学 1.该数据集于 2001 年由意大利北部帕维亚大学校园内的反射光学系统成像光谱仪 (ROSIS) 获得。它有 103 个光谱波段。该数据集由 610 x 340 像素组成,涵盖 9 个主要感兴趣的类别。2.Houston. The Houston dataset was acquired over the University of Houston campus and its surrounding areas in 2012 (Debes et al., 2014). It has 144 spectral bands in the wavelength range of 400–1000 nm and a spatial resolution of 2.5 m. It consists of 349 by 1905 pixels and covers 15 categories. 休斯顿。 休斯顿数据集于 2012 年在休斯顿大学校园及其周边地区获得(Debes et al., 2014)。它有 144 个光谱波段,波长范围为 400-1000 nm,空间分辨率为 2.5 m。它由 349 x 1905 像素组成,涵盖 15 个类别。3.Indian Pines 1. The AVIRIS sensor acquired this dataset in North-west Indiana in 1992. It has a dimension of 145 by 145 pixels and a spatial resolution of 20 m. It covers 200 spectral bands in the wavelength range of 400–2500 nm after removing the water absorption bands. The dataset includes 16 vegetation classes. 印度松树 1.AVIRIS 传感器于 1992 年在印第安纳州西北部采集了这个数据集。它的尺寸为 145 x 145 像素,空间分辨率为 20 m。去除吸水波段后,它覆盖了 400–2500 nm 波长范围内的 200 个光谱波段。该数据集包括 16 个植被类。4.Whu-HongHu. This dataset was collected using a UAV platform in HongHu City in 2017 (Zhong et al., 2020). It comprises 270 spectral bands ranging from 400 to 1000 nm, with a high spatial resolution of approximately 0.04 m. The dimensions of the imagery are 940 by 475 pixels, which includes 17 typical crop types. Whu-洪虎. 该数据集是 2017 年在洪湖市使用无人机平台收集的 (Zhong et al., 2020)。它由 270 个光谱波段组成,范围从 400 到 1000 nm,空间分辨率约为 0.04 m。图像的尺寸为 940 x 475 像素,其中包括 17 种典型的裁剪类型。 我应该如何得到这四个.mat文件
06-24
【博士论文复现】【阻抗建模、验证扫频法】光伏并网逆变器扫频与稳定性分析(包含锁相环电流环)(Simulink仿真实现)内容概要:本文档围绕“博士论文复现”主题,重点介绍了光伏并网逆变器的阻抗建模与扫频法稳定性分析,涵盖锁相环和电流环的Simulink仿真实现。文档旨在通过完整的仿真资源和代码帮助科研人员复现相关技术细节,提升对新能源并网系统动态特性和稳定机制的理解。此外,文档还提供了大量其他科研方向的复现资源,包括微电网优化、机器学习、路径规划、信号处理、电力系统分析等,配套MATLAB/Simulink代码与模型,服务于多领域科研需求。; 适合人群:具备一定电力电子、自动控制或新能源背景的研究生、博士生及科研人员,熟悉MATLAB/Simulink环境,有志于复现高水平论文成果并开展创新研究。; 使用场景及目标:①复现光伏并网逆变器的阻抗建模与扫频分析过程,掌握其稳定性判据与仿真方法;②借鉴提供的丰富案例资源,支撑博士论文或期刊论文的仿真实验部分;③结合团队提供的算法与模型,快速搭建实验平台,提升科研效率。; 阅读建议:建议按文档目录顺序浏览,优先下载并运行配套仿真文件,结合理论学习与代码调试加深理解;重点关注锁相环与电流环的建模细节,同时可拓展学习其他复现案例以拓宽研究视野。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我变了_我没变

随意 。。。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值