【问题标题】:__getattr__ keeps returning None even when I attempt to return values即使我尝试返回值,__getattr__ 也会一直返回 None
【发布时间】:2009-12-23 21:17:29
【问题描述】:

尝试运行以下代码:

class Test(object):
def func_accepting_args(self,prop,*args):
    msg = "%s getter/setter got called with args %s" % (prop,args)
    print msg #this is prented
    return msg #Why is None returned?

def __getattr__(self,name):
    if name.startswith("get_") or name.startswith("set_"):
        prop = name[4:]
        def return_method(*args):
            self.func_accepting_args(prop,*args)
        return return_method
    else:
        raise AttributeError, name

x = Test()
x.get_prop(50) #will return None, why?!, I was hoping it would return msg from func_accepting_args 

有人解释为什么返回 None 吗?

【问题讨论】:

    标签: python metaprogramming


    【解决方案1】:

    return_method() 不返回任何内容。它应该返回包装好的func_accepting_args() 的结果:

    def return_method(*args):
        return self.func_accepting_args(prop,*args)
    

    【讨论】:

    • 天哪!从工作日浪费了 10 个小时.. 在 stackoverflow 上花了不到一分钟的时间来解决:D
    【解决方案2】:

    因为 return_method() 不返回值。它只是从底部掉出来,因此你得到 None。

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 1970-01-01
      • 2019-07-09
      • 2021-05-26
      • 1970-01-01
      • 2022-07-12
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多