-1

for some reason I can't figure out why my code prints "None" after printing something out of a class or how to remove it. This is my code:

class armour:
    def __init__(self, name, defence):
        self.name = name
        self.defence = defence

    def block(self):
        print("your " + self.name + " blocked " + str(self.defence) + "\n")

class weapon:
    def __init__(self, name, attack):
        self.name = name
        self.attack = attack

    def attacks(self):
        print("your " + self.name + " blocked " + str(self.attack) + "\n")

loot = {
    "id1" : armour("test 1", 10),
    "id2" : weapon("test 2", 10),
}

equipment = {
    "armour" : loot["id" + str(1)],
    "weapon" : loot["id" + str(2)],
}


print(equipment["armour"].name)
print(equipment["armour"].block())
print(equipment["weapon"].name)
print(equipment["weapon"].attacks())

If anyone could also explain why it is happening it would be appreciated.

crazy da gamer
  • 11
  • 1
  • 2
  • 5

3 Answers3

3

In python every function returns a value. If you do not specify it will return None. If you print the function invocation on that It will print None.

def none_func():
    pass

print(none_func())
None

In your code you are substantially doing the same.

print(equipment["armour"].block())

Here you are printing the invocation of block() method.

Rahul
  • 10,830
  • 4
  • 53
  • 88
0

It print None because the function call inside the print statement does not return anything. Just make function calls and remove the print for them. Or return strings. For example:

print(equipment["armour"].name)
equipment["armour"].block()
print(equipment["weapon"].name)
equipment["weapon"].attacks()
Axeon Thra
  • 334
  • 3
  • 14
  • This is, however, the reason that each method should *return* a value rather than printing a value itself. The caller can always decide whether to print the return value or not; the caller *cannot* "unprint" a value. – chepner Mar 13 '18 at 18:36
0

Your weapon.attacks method doesn't have an explicit return value, so it returns None. When you call print(equipment["weapon"].attacks()) you're printing out the return value, which is None. Either change the method to return the "your " + self.name + " blocked " + str(self.attack) + "\n" string, and then print it, or just call the method and let it do the printing, without printing the return value.

Basically change your last line to this:

#print(equipment["weapon"].attacks())
equipment["weapon"].attacks()
mypetlion
  • 2,415
  • 5
  • 18
  • 22