如何在面向对象编程中在Python中创建列表?

2 投票
3 回答
4303 浏览
提问于 2025-04-16 13:45

我正在尝试创建一个初始属性,同时也想生成一个列表。

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.")

3 个回答

0

你在构造函数里使用了属性 self._items,但在其他地方却用的是 self.items

这可能就是你遇到的问题。如果不是这样的话,你需要更清楚地说明你遇到的问题是什么。

1

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这种时候,我们需要去查找原因,看看哪里出了问题。通常,我们可以通过查看错误信息来帮助我们找到问题所在。

错误信息就像是程序给我们的提示,告诉我们哪里出了问题。它可能会告诉我们是哪个文件出错了,或者是哪个行数有问题。通过这些信息,我们可以更快地定位到错误的地方。

另外,很多时候我们可以在网上找到类似的问题和解决方案,比如在StackOverflow这样的论坛上。这里有很多程序员分享他们的经验和解决办法,我们可以借鉴他们的思路,找到解决自己问题的方法。

总之,遇到问题时不要慌张,仔细查看错误信息,利用网络资源,通常都能找到解决方案。

try:
    inp = raw_input  # Python 2.x
except NameError:
    inp = input      # Python 3.x

def describe(lst):
    if not lst:
        return "nothing"
    elif len(lst)==1:
        return "a {0}".format(lst[0])
    else:
        return 'a {0}, and a {1}'.format(', a '.join(lst[:-1]), lst[-1])

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

    def __init__(self, name, items=None, max_items=5):
        super(Player,self).__init__()
        self.name = name
        self.max_items = max_items
        self.items = list(items)[:max_items] if items else []
        print("A new player named {0} has been created.".format(self.name))

    def inventory(self):
        if self.items:
            print("Your pockets contain: {0}.".format(describe(self.items)))
        else:
            print("Your pockets are empty.")

    def take(self, new_item):
        if len(self.items) < self.max_items:
            self.items.append(new_item)
            print("You take the {0}.".format(new_item))
            return True
        else:
            print("Your pockets are too full.")
            return False

    def drop(self, drop_item):
        try:
            self.items.remove(drop_item)
            print("You drop the {0}.".format(drop_item))
            return True
        except ValueError:
            print("You have no {0}!".format(drop_item))
            return False

def main():
    print("Welcome, adventurer! What is your name?")
    char = Player(inp(), ['string', 'blue key', 'pocketknife'])

    commands = ['go', 'take', 'drop', 'inv', 'help', 'quit']
    roomItems = ['ball', 'apple', 'dragon']
    while True:
        print("You are in the Baron's antechamber. You see {0}.".format(describe(roomItems)))

        cmd = [i.lower() for i in inp('> ').strip().split()]
        verb = cmd[0]
        if verb in commands:
            if verb=='go':
                dir = ' '.join(cmd[1:])
                print('You try to go {0}, but a giant kangaroo kicks you back into the antechamber.'.format(dir))
            elif verb=='take':
                item = ' '.join(cmd[1:])
                if item in roomItems and char.take(item):
                    roomItems.remove(item)
            elif verb=='drop':
                item = ' '.join(cmd[1:])
                if char.drop(item):
                    roomItems.append(item)
            elif verb=='inv':
                char.inventory()
            elif verb=='help':
                print("I know the words {0}.".format(', '.join(commands)))
            elif verb=='quit':
                break
        else:
            print("I don't know how to '{0}'.".format(verb))

    print('The Baron has decided! There is a grating noise - the floor drops away like a trapdoor, and {0} plummets into darkness. THE END!'.format(char.name))

if __name__=="__main__":
    main()
    inp("Press enter to exit.")
2

self._items = [] 这行代码是完全正确的。

但是你的代码里有一些逻辑错误:

if len(self.items) > 1: 这句应该改成 if len(self.items) > 0:,或者更好的是 if self.items: - 你想检查的是列表里是否有一个或更多的项目,而不是检查是否有超过一个项目。

撰写回答