2013-09-24 89 views
0

我有一个程序,基本上做到这一点:方法返回类型“nonetype”不是类型'字典”

class principal(): 
    def execute(self): 
     x = calculate() 
     final = x.vars1() 
     print str(type(final)) 

class calculate(): 
    def __init__(self): 
     t = self.vars1() 
    def vars1(self): 
     a = {} 
     for i in xrange(0,10): 
      a[i] = i*10 

     self.result(a) 

    def result(self,r): 
     return r 


m = principal() 
x = m.execute() 

我的回报是‘型‘NoneType’’ 为什么没有返回一个字典类型,女巫我期望的是什么?

回答

1

。在你的方法没有回报,因此它返回None

vars1方法更改为:

def vars1(self): 
    a = {} 
    for i in xrange(0,10): 
     a[i] = i*10 
    return a 

你不能打电话做回你尝试过的方法。 return语句允许你将一个对象返回给函数的调用者。你的功能result是参数r基本上回到方法vars1。但是vars1不会返回任何东西,除非你在这里也提供了返回语句。

1

,你必须返回一个快译通,你的函数没有返回任何值。这有时称为功能的结束。每种语言都有不同的看法,但最重要的是要明确。例如,在功能vars1你应该在末尾添加一个return声明:

def vars1(self): 
    a = {} 
    for i in xrange(0,10): 
     a[i] = i*10 

    return self.result(a) 

目前,vars1(self)是“脱落到底”,没有返回值和Python实际上将返回一个NoneType

return语句返回从函数的值。没有表达式参数的情况下返回None。落在函数的末尾也会返回None。

这里是doc

1

你不返回从vars1方法什么。您需要return a而不是self.result(a)

调用另一个函数return不起作用,它看起来像你认为它的方式。您的result方法本质上是无操作的;它只是将其输入返回给它所调用的任何东西。它不会奇迹般地将该输入从堆栈上的其他方法中返回。您vars1方法没有return语句,因此它不会返回任何东西。

你的流量看起来有点像这样的时刻:

m.execute() 
    creates x 
    -> calls x.vars1() 
     creates a 
     -> calls x.result(a) 
      -> returns a 
      <- 
     discards the return value of x.result() 
     returns None 
     <- 
    assigns the return value of x.vars1() to final 
    prints str(type(final)), which is None 

你想要的是它看起来像这样:

m.execute() 
    creates x 
    -> calls x.vars1() 
     creates a 
     returns a 
     <- 
    assigns the return value of x.vars1() to final 
    prints str(type(final)), which is a 
相关问题