Reputation: 81
I was making a simple method that would return a list of a classes attribute values. It works fine but at the end of the list being printed there is always 'None' displayed as well. I am not sure why. Any clarification?
Here is my code: Player Class
class Player:
def __init__(self, name, caps, inventory, caravans):
self.name = name
self.caps = caps
self.inventory = inventory
self.caravans = caravans
Inventory Class and it's methods, I am referring to the list method.
class Inventory:
"""Items are stored by value not quantity"""
def __init__(self, weapons_ammo, meds_chems, armor):
self.weapons_ammo = weapons_ammo
self.meds_chems = meds_chems
self.armor = armor
def list(self):
"""List all inventory values."""
print(f'Weapons & Ammo: {self.weapons_ammo}\n'
f'Meds & Chems: {self.meds_chems}\n'
f'Armor: {self.armor}')
Instances
example_inventory = Inventory(5000, 2000, 1500)
example_player = Player('John', 10000, example_inventory, 3)
When I run this code:
print(example_player.inventory.list())
I get:
Weapons & Ammo: 5000 Meds & Chems: 2000 Armor: 1500 None
But when I run it without the print function:
example_player.inventory.list()
I get the proper return I was looking for with the 'None' at the end.
Could anyone explain why this is? I'm assuming it has to do with the method already calling the print function.
Thank you!
Upvotes: 1
Views: 831
Reputation: 6930
print(example_player.inventory.list())
prints the return value of the example_player.inventory.list()
method; since there's no return
statement in the method, the return value is None
.
The print
inside the method prints "Weapons & Ammo: 5000 Meds & Chems: 2000 Armor: 1500" and then the print
outside prints "None"
Upvotes: 1
Reputation: 77857
You specifically print
ed the return value of the function:
print(example_player.inventory.list())
Your list
function has no explicit return; the default value is None
. This has nothing to do with having another print
insides the function, merely that you didn't return anything.
I think that all you want to do is to execute the function:
example_player.inventory.list()
BTW, it's very bad form to "shadow" a built-in type: don't use list
as a function name. Something such as show_inventory
would be better.
Upvotes: 2