gpt4 book ai didi

python - 使用面向对象编程时如何在 Python 中创建列表?

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:37 24 4
gpt4 key购买 nike

<分区>

我正在尝试创建一个同时创建列表的初始属性。

class Player(object):
"""A virtual player"""

def __init__(self, name, items, max_items = 5):
# still need to create item list
self._items = []
self.name = name
self.max_items = max_items
print "\nA new player named",self.name,"has been created.\n"

def inventory(self):
if len(self.items) > 1:
print "\nThe inventory is:"
print self.items
else:
print "Your inventory is empty"

def take(self, new_item):
if self.items <= self.max_items:
self.items.append(new_item)
else:
print "\nSorry, your inventory is completely full."

def drop(self, drop_item):
if drop_item not in self.items:
print "That item does not exist in your inventory."
else:
self.items.remove(drop_item)



def main():
player_name = raw_input("What name do you want to give the player?: ")
player = Player(player_name)

choice = None
while choice != 0:
print \
"""
Player Menu

0 - Quit
1 - Print inventory
2 - Add an item
3 - Drop an item
"""
try:
choice = int(raw_input("Choice: "))
except (ValueError):
print "Invalid number."

if choice == 0:
print "\nGoodbye\n"
elif choice == 1:
player.inventory()
elif choice == 2:
new_item = raw_input("What item do you wish to add to your inventory?: ")
new_item = new_item.lower()
player.take(new_item)
elif choice == 3:
drop_item = raw_input("What item do you want to drop?: ")
drop_item = drop_item.lower()
player.drop(drop_item)


# main
main()
raw_input("\nPress enter to exit.")

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com