欢迎加入QQ讨论群258996829
麦子学院 头像
苹果6袋
6
麦子学院

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

发布时间:2018-04-11 22:50  回复:0  查看:2304   最后回复:2018-04-11 22:50  
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 我们就继续输入参数直到满足函数的需求。
来源: 博客园
您还未登录,请先登录

热门帖子

最新帖子