首页 > 编程语言 >关于python反射机制中的参数问题处理

关于python反射机制中的参数问题处理

时间:2023-06-18 21:36:13浏览次数:45  
标签:反射 name python self default command act 参数 weapon

关于python反射机制中的参数问题处理

 

python的反射机制十分的常用,主要是字符串与模块应用之间的连接方法。核心是将字符串转换成可以调用模块、模块方法的变量。

主要包括了以下四个方法:

hasattr(obj, name, /)

Return whether the object has an attribute with the given name.

This is done by calling getattr(obj, name) and catching AttributeError.

hasattr()是检测obj里面是否包含了name属性(函数、方法……),hasattr()返回True或者False。

 

getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.

When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.

getattr()用来调用object.name,一般可将其赋值给其他变量。default是可选项,同样是object.name不存在的条件下,在不填的时候将返回AttributeError;如果设置了default值,则返回用户设置的default值。

 

setattr(obj, name, value, /)

Sets the named attribute on the given object to the specified value.

setattr(x, 'y', v) is equivalent to “x.y = v”

setattr()设置一个obj.name = value,也就是说设置一个新的方法(函数)到对象里面。

 

delattr(obj, name, /)

Deletes the named attribute from the given object.

delattr(x, 'y') is equivalent to ``del x.y''

delattr()删除obj.name,把对象里不需要的方法(属性)去除。

 

设置一个十分简单的人物属性代码

class role(object):
    def __init__(self, name, weapon, clothes, life = 100):
        self.name = name
        self.weapon = weapon
        self.clothes = clothes
        self.life = life

    def buy_weapon(self, weapon_name):
        print("%s buy a %s" %(self.name, weapon_name))

    def got_headshoot(self):
        print("%s got headshot!" %self.name)
        self.live -= 50

    def show_life(self):
        print("Life is %s" %self.life)

    def __del__(self):
        print("Game Over!")

role_default = role("zzz", "AWM", "3-level")

while True:
    command = input('action:')
    if hasattr(role_default, command):
        command_act = getattr(role_default,command)
        command_act()
    else:
        print('Command not exists!')

 

在运行的过程中,command输入除了buy_weapon以外的字符串都是没有问题的。

那就来找找看buy_weapon这个函数跟其他方法有什么不同呢?

原来是buy_weapon是一个带有两个参数的函数,包括的额外的'weapon_name'。那我们来看一下报错信息:

TypeError: buy_weapon() missing 1 required positional argument: 'weapon_name'

跟我们猜测的一样,果然是少了一个参数。

 

定位到代码上,我们可以知道Error出现在:

command_act()

也就是command_act调用的时候缺少了参数'weapon_name',于是我们想到了一个笨拙的方法(传参1.0):

while True:
    command = input('action:')
    if hasattr(role_default, command):
        command_act = getattr(role_default,command)
        try:
            command_act()
        except TypeError:
       factor = input('Needing a extra factor:')
       command_act(factor)
else: print('Command not exists!')

我们只需要简单的添加一下try判断,如果判断出来TypeError就给他传个参数就好了呗!

在代码后期的拓展中发现,我们要传两个参数怎么办??结果是我们又缺少了一个参数,那如果以后要传三个、四个、甚至一万个参数呢?就只能如同以下代码一样不停地增加try-except个数,这样子将会大大地增加工作量。

try:
    command_act()
    except TypeError:
        V1 = input('Missing Variable:')
        try:
            command_act(V1)
        except TypeError:
            V2 = input('Missing Variable2:')
            command_act(V1,V2)

 

于是我们想到设置一个循环去判断到底应该传多少个参数进去以及把用户输入当作参数传到函数:

要用到一个比较冷门的代码用了统计函数所需参数的个数:parameter_count = command_act.__code__.co_argcount

我们在知道所需参数个数后定义一个空列表用来“装”这些参数的值,接下来我们写一个循环来让用户循环输入所需要的参数。

接下来我们可以学到一个额外的知识,用来批量生产变量名:

names = locals()
names['v%s'%i] = input('Input Variable:')

locals()是python用来管理变量的字典,py文件中的变量名被储存到locals()字典里作为key,值为value。

最后用到一个很重要的知识,把列表转换成为参数传入函数: function(*list),总体代码如下:

class role(object):
    def __init__(self, name, weapon, clothes, life = 100):
        self.name = name
        self.weapon = weapon
        self.clothes = clothes
        self.life = life

    def buy_weapon(self, weapon_name):
        print("%s buy a %s" %(self.name, weapon_name))

    def got_headshoot(self):
        print("%s got headshot!" %self.name)
        self.life -= 50

    def fight(self,weapon,place):
        print("%s use %s to shoot %s" %(self.name,weapon, place))


    def show_life(self):
        print("Life is %s" %self.life)

    def __del__(self):
        print("Game Over!")

role_default = role("zzz", "AWM", "3-level")





while True:
    command = input('action:')
    if hasattr(role_default, command):
        command_act = getattr(role_default,command)
        parameter_count = command_act.__code__.co_argcount
     if parameter_count == 1: # self is also a parameter no need to input command_act() else: v_list = [] for i in range(1,parameter_count): parameter = input('Input Variable:') v_list.append(parameter) command_act(*v_list) else: print('Command not exists!')

 

该代码就可以实现无限参数的传入,这样我们在不改变类里面的代码逻辑和代码的条件下,完成了无论类里面的函数有多少参数都可以通过用户输入来解决。

 

标签:反射,name,python,self,default,command,act,参数,weapon
From: https://www.cnblogs.com/-hz01/p/17489775.html

相关文章

  • python 爬取原力文档日语学习资料
    参考https://blog.csdn.net/weixin_46184311/article/details/115291441代码importrequests,json,re,time,urllib.requestimporttimeimportwgetdefgetParameter(url):#获取文档参数text_response=requests.get(url=url,headers=headers).textactu......
  • 工作提效--python实现批量音频裁剪工具
    一、问题:大批量的音频测试文件,无法满足测试需求项目测试需要往平台中上传一批音频文件进行算法测试,平台规定的音频的时长必须在10-30s内,而从算法开发人员那里获取到的3000条音频文件都是32s时长,因此无法将测试数据上传到平台进行测试。基于以上问题,需要在项目体测之前将3000......
  • python+tkinter开发2048游戏
    1.界面设计如果开发这个游戏,相信一定玩过。这里不过多介绍。我最后的效果。2.代码importrandomimporttkinterastkfromtkinterimportmessageboxfromtkinter.constantsimportW,N,E,Sdefrandom_2()->bool:"""在空位置随机生成一个2:ret......
  • python 并发编程-3
    Python中的并发编程-3爬虫是典型的I/O密集型任务,I/O密集型任务的特点就是程序会经常性的因为I/O操作而进入阻塞状态,比如我们之前使用requests获取页面代码或二进制内容,发出一个请求之后,程序必须要等待网站返回响应之后才能继续运行,如果目标网站不是很给力或者网络状况不是很......
  • Python之异常处理
    try: 可能会出现异常的代码except你要捕捉的异常1处理: 对这个异常的处理except你要捕捉的异常2处理: 对这个异常的处理else: 没出现异常时做的处理finally: 不管有没有出现异常,都会执行的代码#else,finally这些词的顺序不可以变importsystry:n=int(input()......
  • 【Python】在同一图形中更加优雅地绘制多个子图
    1.引言数据可视化非常重要,有一句俗语叫做一图顶千言,我相信好多小伙伴应该都听说过这句话;即使是有人第一次听到,我想应该也会觉得赞成,这足以说明数据可视化的重要性。我们在前一篇博客中,介绍了如何利用subplot来在一张子图里绘制多个子图,最近我又发现了一种更加优雅地实现,迫不及待地......
  • Python编程和数据科学中的数据处理:如何从数据中提取有用的信息和数据
    目录引言数据分析和数据处理是数据科学和人工智能领域的核心话题之一。数据科学家和工程师需要从大量的数据中提取有用的信息和知识,以便更好地理解和预测现实世界中的事件。本文将介绍Python编程和数据科学中的数据处理技术,帮助读者从数据中提取有用的信息和数据。技术原理......
  • Python编程和数据科学中的人工智能:如何创建复杂的智能系统并提高模型性能
    目录1.引言2.技术原理及概念3.实现步骤与流程4.应用示例与代码实现讲解标题:《Python编程和数据科学中的人工智能:如何创建复杂的智能系统并提高模型性能》1.引言人工智能(AI)是一个广泛的领域,涵盖了许多不同的技术和应用。在Python编程和数据科学中,人工智能是一个非常重要......
  • Python编程和数据科学中的大数据分析:如何从大量数据中提取有意义的信息和模式
    目录《Python编程和数据科学中的大数据分析:如何从大量数据中提取有意义的信息和模式》引言大数据时代已经来临,随着互联网和物联网的普及,海量数据的产生和存储已经成为一种普遍的现象。这些数据包含各种各样的信息,如文本、图像、音频和视频等,而大数据分析则是将这些海量数据中提......
  • python常用操作之代码操作大全
    目录列表操作大全(listoperations)字典操作大全(dictionaryoperations)表格操作大全(DataFrameoperations)MySQL操作大全(MySQLoperations)列表操作大全(listoperations)字典操作大全(dictionaryoperations)表格操作大全(DataFrameoperations)MySQL操作大全(MySQLoper......