简体   繁体   中英

Object-oriented programming error

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM