现在的位置: 首页 > 综合 > 正文

python 3中使用getattr和*args时, 出现传入参数不一致的问题

2013年08月24日 ⁄ 综合 ⁄ 共 435字 ⁄ 字号 评论关闭

今天在用python3的getattr时遇到一个问题, 就是老提示传入参数和函数前面不一致, 代码为:

class Test:
     def __init__(self, name):
          self.name = name

     def execute(self, methodname, *args):
          print(args)
          print(self.name)
          print(getattr(self.name, methodname)(args))

经过调查发现, args在Python3中类似指针, 必须用*args才能传递整个参数, 要不然是第一个参数值。
解决方案:
     def execute(self, methodname, *args):
          print(args)
          print(self.name)
          print(getattr(self.name, methodname)(*args))

抱歉!评论已关闭.