0
class Ammo(Thing):

    # constructor here
    def __init__(self,name,weapon,quantity):
        self.name = name
        self.weapon = weapon
        self.quantity = quantity

    # definition of weapon_type here
    def weapon_type(self):
        return self.weapon

This is my code and when i try to retrieve the weapon_type as a string Here are my Inputs

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())   ## bow 

I don't get bow instead I get <__main__.Weapon object at 0x0211DCB0>

4
  • 3
    What does "I can't Inputs" mean? Commented Apr 5, 2014 at 5:04
  • 1
    What problem are you having? Also, can you please provide the code for the Weapon class as well? Commented Apr 5, 2014 at 5:08
  • I hope you have defined __str__(self) inside Weapon class Commented Apr 5, 2014 at 5:12
  • Your sample doesn't show any error, and you don't tell what the problem is. What do you expect to get? What do you get instead? Commented Apr 5, 2014 at 6:10

1 Answer 1

5

arrows.weapon_type() will currently return a Weapon rather than a string. print will convert it for you, but I'm guessing it's printing something like this:

<__main__.Weapon object at 0x7ffea6de6208>

to get it to print something more useful, you can control how it converts to string. Print calls the builtin function str on its arguments, which calls the method __str__ - in other words, if you define your Weapon class like this:

class Weapon:
    # other methods
    def __str__(self):
        return self.type + " weapon"

then str(a_weapon), and by extension print(a_weapon) will do something more sensible.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually I got it simply by returning str(self.weapon)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.