2

So, I'm making a text based game to learn the python language. and I can't get the return function working...

Here is my code;

class Weapon:
    def __str__(self):
        return self.name

class WoodenStaff(Weapon):
    def __init__(self):
        self.name = "Wooden Staff"
        self.description = "Basic Staff"
        self.damage = 5

inventory = [WoodenStaff()]
print (inventory)

After I run this I got:

[<__main__.WoodenStaff object at 0x000001E9F192CAC8>]
GIZ
  • 4,409
  • 1
  • 24
  • 43
Mizuchi
  • 53
  • 5
  • Possible duplicate of [Python \_\_str\_\_ and lists](http://stackoverflow.com/questions/727761/python-str-and-lists) – syntonym May 15 '16 at 18:47

3 Answers3

3

You need to implement __repr__ because your object is inside a list.

class Weapon:
    def __str__(self):
        return self.name

    def __repr__(self):
        return self.name

class WoodenStaff(Weapon):
    def __init__(self):
        self.name = "Wooden Staff"
        self.description = "Basic Staff"
        self.damage = 5

inventory = [WoodenStaff()]
print (inventory)
>> [Wooden Staff]

Without implementing __repr__, you get the expected output if iterating over the list:

class Weapon:
    def __str__(self):
        return self.name

class WoodenStaff(Weapon):
    def __init__(self):
        self.name = "Wooden Staff"
        self.description = "Basic Staff"
        self.damage = 5

inventory = [WoodenStaff()]
for weapon in inventory:
    print(weapon)
>> Wooden Stuff
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

You need to define __repr__ as well

 def __repr__(self):
      return self.name

e.g. -

>>> class Weapon:
...     def __str__(self):
...         return self.name
...     def __repr__(self):
...         return self.name
...
>>> class WoodenStaff(Weapon):
...      def __init__(self):
...         self.name = 'Foo'
...
>>> [WoodenStaff()]
[Foo]
Pythonista
  • 11,377
  • 2
  • 31
  • 50
0

Just add a __repr__ method to WoodenStaff Class

GIZ
  • 4,409
  • 1
  • 24
  • 43
0n10n_
  • 382
  • 3
  • 10