【问题标题】:Why is my code printing 'None'?为什么我的代码打印“无”?
【发布时间】:2013-08-20 05:57:21
【问题描述】:

我的代码可以在这里找到:https://github.com/thekarangoel/HackerNewsAPI/blob/master/hn.py

测试用例是这样的:

from hn import HN

hn = HN()

for story in hn.get_top_stories()[:10]:
    print story.print_story()
    print '*' * 50
    print ''

这样打印我的输出:

.....
.....
.....
**************************************************

Rank: 3
Story ID: 6231993
Title: Pipe Dream? 3D-Printed Model of Hyperloop Created
Link: http://news.yahoo.com/pipe-dream-3d-printed-model-hyperloop-created-192033757.html
Domain: yahoo.com
Points: 1
Submitted by: evo_9
Number of comments: 0
Link to comments: http://news.ycombinator.com/item?id=6231993
None
**************************************************

Rank: 4
Story ID: 6231992
Title: What colour are your bits?
Link: http://ansuz.sooke.bc.ca/entry/23
Domain: bc.ca
Points: 1
Submitted by: grey-area
Number of comments: 0
Link to comments: http://news.ycombinator.com/item?id=6231992
None
.....
.....

注意到每张印刷品末尾的None 了吗?为什么会在那里?代码有什么问题?

【问题讨论】:

    标签: python class python-2.7 printing nonetype


    【解决方案1】:

    好像story.print_story() 没有返回任何东西。

    如果函数没有返回,则返回None

    >>> def a():
    ...     print 1
    ...
    >>> print a()
    1
    None
    

    print story.print_story() 中删除print

    【讨论】:

      【解决方案2】:

      代码中的所有函数调用都替换为函数的返回值。默认情况下,所有函数都返回 None。如果你的函数中有 return 语句,那么 return 语句中指定的值将被返回而不是 None。

      在这一行:

      print story.print_story()
      

      函数调用:

      story.print_story()
      

      替换为 print_story() 的返回值。 print_story() 方法中没有 return 语句,所以它默认返回 None,给你这个:

      print None
      

      【讨论】:

        【解决方案3】:

        您的print_story 似乎没有返回任何内容。只需将print story.print_story() 替换为story.print_story()

        这是一个正在发生的事情的例子:

        >>> def print_story():
        ...     print "story"
        ... 
        >>> print print_story()
        story
        None
        >>> print_story()
        story
        

        【讨论】:

          猜你喜欢
          • 2023-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-14
          • 1970-01-01
          相关资源
          最近更新 更多