class Ammo(Thing):
def __init__(self, name, weapon, quantity):
self.name=name
self.weapon=weapon
self.quantity=quantity
def get_quantity(self):
return self.quantity
def weapon_type(self):
return self.weapon
def remove_all():
self.quantity=0
bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())
output of print(arrows.weapon_type()) is supposed to be bow but I got <__main__.Weapon object at 0x10441f0b8> instead. How can I modify my code so that it returns bow?
Below is class Weapon:
import random
class Weapon(Thing):
def __init__(self, name, min_dmg, max_dmg):
self.name=name
self.min_dmg=min_dmg
self.max_dmg=max_dmg
def min_damage(self):
return self.min_dmg
def max_damage(self):
return self.max_dmg
def damage(self):
return random.randint(self.min_dmg,self.max_dmg)
3 Answers 3
I think the best way to do it would be overriding the str function in Weapon.
adding:
def __str__(self):
return self.name
to your weapon class should fix it.
Comments
It depends on what do you want to print.
bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())
The name of object:
bow = Weapon('bow', 10, 20)
# \_______ name of object
so you have to:
print(arrows.weapon_type().name)
# it will print bow
or your object itself:
bow = Weapon('bow', 10, 20)
# \____________________ object
I personally prefer print the name I passed in arguments, so if I call my object bow and pass "hardened_bow", 10, 20 as arguments it will print "hardened_bow" and not "bow"
Comments
Add repr to Weapon class:
def __repr__(self):
return self.name
object.__repr__(self)
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines repr() but not str(), then repr() is also used when an "informal" string representation of instances of that class is required.
This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
object.__str__(self)
Called by the str() built-in function and by the print statement to compute the "informal" string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.
return self.weapon.nameinsideweapon_type. You are returning (and then printing) the entireWeaponobject instead of just the name.