所以,我正在制作一个基于文本的游戏来学习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>]
答案 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
方法即可