我不能让返回功能工作

时间:2016-05-15 18:19:18

标签: python

所以,我正在制作一个基于文本的游戏来学习python语言。我无法使返回功能正常工作......

这是我的代码;

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)

我跑完之后得到了:

[<__main__.WoodenStaff object at 0x000001E9F192CAC8>]

3 个答案:

答案 0 :(得分:3)

您需要实现__repr__,因为您的对象位于列表中。

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]

如果没有实现__repr__,如果遍历列表,则会得到预期的输出:

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

答案 1 :(得分:2)

您还需要定义__repr__

 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]

答案 2 :(得分:0)

只需向__repr__班级

添加WoodenStaff方法即可