2009-12-23 49 views
1

尝试运行下面的代码:__getattr__保持返回无,甚至当我试图返回值

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?

回答

6

return_method()不返回任何东西。它应该返回的包裹func_accepting_args()结果:

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

omg!从工作日浪费了10个小时..花了不到一分钟的时间来解决stackoverflow:D – 2009-12-23 21:25:46

1

因为return_method()没有返回值。它只是跌破底部,因此你得到无。