基本上,我有一个游戏玩家的课程
class Player:
def __init__(self,inventory,hp):
self.inventory = []
self.hp = 20
...
...
P = Player()
我只想检查清单中的项目(项目也是每个类别)
class Book():
def __init__(self,name,description):
...
...
然后这样做。
if Book() in P.inventory:
print("You have a book.")
else:
print("You don't have a book.")
我遇到的问题是,即使Book()
对象位于播放器的广告资源中,它也会将if
语句读为false并运行{{1}声明。
我以为我可以尝试使用像这样的else
循环
for
但是我希望我不必为这么简单的任务使用那么多代码。
答案 0 :(得分:1)
Book()
每次都会创建一个新对象,因此Book() == Book()
会返回False
。您可能希望使用isinstance
代替:
a_book = Book()
isinstance(a_book, Book)
有类似的东西:
def check_for_books(inventory):
for i in inventory:
if isinstance(i, Book):
print("You have a book.")
return
else:
print("You have no books.")
答案 1 :(得分:1)
实际上,如果只是关心这本书,将书籍与同一本书的名称和描述相同。您最好覆盖本书的eq和hash方法。
class Player:
def __init__(self, inventory=None, hp=None):
if inventory is None:
inventory = []
self.inventory = inventory
self.hp = hp
class Book:
def __init__(self, name, description):
self.name = name
self.description = description
def __eq__(self, other):
return other and self.name == other.name and self.description == other.description
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash((self.name, self.description))
player = Player([Book('Harry Potter', 'Volume I'), Book('Harry Potter', 'Volume II')], 20)
print(Book('Harry Potter', 'Volume I') in player.inventory) # True
print(Book('Harry Potter', 'Volume V') in player.inventory) # False
所以你不必担心你想要检查的书是否恰好是记忆中的实例。由于在大多数情况下,您的数据应存储在db中,而不是存储在内存中。
答案 2 :(得分:0)
这有效:
>>> class Book():
... def __init__(self,name,description):
... self.name = name
... self.description = description
...
>>> class Player:
... def __init__(self,inventory,hp):
... self.inventory = inventory
... self.hp = hp
...
>>> b = Book('myname', 'mydesc')
>>> p = Player([b], 'hp')
>>> b in p.inventory
True
返回False,因为它是Book的另一个实例:
>>> c = Book('myname', 'mydesc')
>>> c in p.inventory
False
答案 3 :(得分:0)
您必须检查广告资源中项目的对象类型,看它们是否属于班级Book()
for o in P.inventory:
if isinstance(o, Book()):
print("You have a book.")
break
else:
print("You don't have a book.")
请注意else
语句是for
语句的一部分,而不是if
语句