首页 > 解决方案 > 输出显示列表的位置而不是实际列表

问题描述

get_objects 函数是返回并显示位置的内容,>[< main .things object at 0x000002624BB2BDF0>] 这是我第一次做 OOP。如何显示实际列表。

class room():

    def __init__(self, name):
        self.__exits = {}
        self.__name = name
        self.__description = None
        self.__objects = []

    def add_objects(self, things):
        self.__objects.append(things)

    def get_objects(self):
        return self.__objects

class things(room):

    def __init__(self, name, is_weapon):
        self.name = name
        self.weapon = is_weapon

    def weapon(self):
        self.is_weapon = True

    def not_weapon(self):
        self.is_weapon = False
currentRoom = center
alive = True
while alive:

    print(currentRoom.get_name())
    print(currentRoom.get_desc())
    print("Objects here: ",currentRoom.get_objects())  

标签: pythonpython-3.xlistoop

解决方案


既然你说你是 OOP 的新手,我的第一个问题是你为什么要命名所有属性?有关python 名称修饰的讨论以及通常为什么应该避免它,请参阅此问题。

如果您选择不使用名称修饰,则不需要“getter”方法,因为您可以简单地访问对象属性:

class room():

    def __init__(self, name):
        self.exits = {}
        self.name = name
        self.description = None
        self.objects = []

while alive:

    print(currentRoom.name)
    print(currentRoom.description)
    print("Objects here: ",currentRoom.objects) 

与 setter 方法类似,您可以使用:

curretRoom.objects.append('chair')

有关使用 getter 和 setter 的方法,请参阅问题,但为什么不需要。

同样,对于您的things班级,我建议您执行以下操作:

class things(room):

    def __init__(self, name, is_weapon):
        self.name = name
        self.is_weapon = is_weapon

然后通过执行以下操作查询一个东西以查看它是否是武器:

chair = things('chair', is_weapon=True)
print(chair.is_weapon)  # prints 'True'

如果你后来决定椅子不是武器:

chair.is_weapon = False
print(chair.is_weapon)  # prints 'False' 

推荐阅读