码迷,mamicode.com
首页 > Web开发 > 详细

Python反射机制中参数问题如何处理?

时间:2018-04-11 22:51:45      阅读:361      评论:0      收藏:0      [点我收藏+]

标签:

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):
n = "zzh"
date = "2018"
def __init__(self, name, weapon, clothes, live = 100):
self.name = name
self.weapon = weapon
self.clothes = clothes
self.live = live
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_inner(self):
print("Live is %s" %self.live)
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)elseprint(’Command not exists!’)
我们只需要简单的添加一下try判断,如果判断出来TypeError就给他传个参数就好了呗!
在代码后期的拓展中发现,我们要传两个参数怎么办??结果是我们又缺少了一个参数,那如果以后要传三个、四个、甚至一万个参数呢?
我们必须要找到一个方法一劳永逸地解决这个问题!首先,我们可以知道的是,所有的参数都是依赖用户输入的,也就是如果有一万个参数,用户则需要输入一万次。
于是我们联想到了循环,通过判断TypeError出现与否来实现循环输入,只要运行结果是TypeError我们就继续输入参数直到满足函数的需求。
来源:博客园

Python反射机制中参数问题如何处理?

标签:

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
wjunxi
加入时间:2017-06-15
  关注此人  发短消息
文章分类
wjunxi”关注的人------(0
wjunxi”的粉丝们------(0
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!