【问题标题】:Output showing location of list instead of actual list输出显示列表的位置而不是实际列表
【发布时间】:2020-09-06 04:14:49
【问题描述】:

get_objects 函数是返回并显示位置的内容,>[ma​​in.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())  

【问题讨论】:

    标签: python python-3.x list oop


    【解决方案1】:

    既然你说你是 OOP 的新手,我的第一个问题是你为什么要命名所有属性?请参阅this question 了解有关 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 的方法,请参阅this 问题,但为什么不需要。

    同样,对于您的 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' 
    

    【讨论】:

    • 我真的不知道 mangling 是什么名字,我的老师只是把它放进去了。那么,房间里的东西,它们也可以在另一个列表中,在另一个班级吗?谢谢。
    • 名称修饰是您在属性名称前面获得(并且我已删除)的双下划线。它的作用是对外部用户隐藏属性,但通常被认为是非 Python 的。我分享的链接是一个很好的资源,还有一个快速的谷歌。
    • 是的,things 对象可以附加到任意数量的room 对象上
    • 如何设置描述?像这样,room.description("This is room")?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多