Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

python - Why does this script print an extraneous 'none' in the output

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

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 "
"
    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()

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
print player.stats()

Is the culprit. player.stats() == None

You want just:

player.stats()

You'd do better to name your function player.printStats().


Another option would be to make it return a string:

def stats(self):
    return '
'.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
    ])

And then print player.stats() would behave as expected


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...