为什么此脚本在输出中打印无关的“无" [英] Why does this script print an extraneous 'none' in the output

查看:64
本文介绍了为什么此脚本在输出中打印无关的“无"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的脚本来帮助我更好地理解类的使用.它为游戏生成一个随机角色.我定义了对象,然后在该对象上调用一个函数来打印生成的字符.在打印块的末尾,有一个无关的无",我不确定它来自哪里,也不知道为什么要打印它.这是示例输出:

I've written a simple script to help me better understand using classes. It generates a random character for a game. I defined the object and then call a function on that object that prints out the generated character. At the end of the printed block, there is an extraneous "None" that I'm not sure where it's coming from nor why it's being printed. Here's the sample output:

ted
Strength  : 20
Dexterity : 17
Hit Points: 100
Aura      : 100
Weapon    :  
Spell     :  
Item      :  
Element   :  
--------------------
None

在我的代码中,player.stats() 的最后一行是 print "-" * 20,它显示在None"的正上方.这是定义对象的代码:

In my code, the last line of player.stats() is print "-" * 20 which is displayed right above "None". Here's the code that defines the object:

class Player(object):

def __init__(self, name):
    self.name = name
    self.strength = randint(15, 20)
    self.dexterity = randint(15, 20)
    self.hit_points = 100
    self.aura = 100
    self.weapon = " "
    self.spell = " "
    self.item = " "
    self.element = " "

def stats(self):
    print "\n"
    print self.name
    print "Strength  : %d" % self.strength
    print "Dexterity : %d" % self.dexterity
    print "Hit Points: %d" % self.hit_points
    print "Aura      : %d" % self.aura
    print "Weapon    : %s" % self.weapon
    print "Spell      : %s" % self.spell
    print "Item      : %s" % self.item
    print "Element   : %s" % self.element
    print "-" * 20

然后使用此对象实例化:

The object is then instanced using this:

name = raw_input("Name your character: ")

player = Player(name)
print player.stats()

如有必要,可以在此处在 Pastebin 阅读完整代码.

The complete code can be read here at Pastebin if necessary.

推荐答案

print player.stats()

是罪魁祸首.player.stats() == None

你只想:

player.stats()

最好将函数命名为 player.printStats().

另一种选择是让它返回一个字符串:

Another option would be to make it return a string:

def stats(self):
    return '\n'.join([
        self.name
        "Strength  : %d" % self.strength,
        "Dexterity : %d" % self.dexterity,
        "Hit Points: %d" % self.hit_points,
        "Aura      : %d" % self.aura,
        "Weapon    : %s" % self.weapon,
        "Spell     : %s" % self.spell,
        "Item      : %s" % self.item,
        "Element   : %s" % self.element,
        "-" * 20
    ])

然后 print player.stats() 会按预期运行

这篇关于为什么此脚本在输出中打印无关的“无"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆