python - 输出显示列表的位置而不是实际列表
问题描述
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())
解决方案
既然你说你是 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'
推荐阅读
- php - 如何在functions.php中获取数据
- python - pygame - while循环使pygame窗口冻结/我如何将子弹射出玩家?
- javascript - 使用 JavaScript 我想要以下输出
- ios - SwiftUI 将 Label 的垂直对齐方式更改为居中图像和文本
- javascript - 猫头鹰轮播导航效果
- python - Blender Python 语句控制台日志记录
- webstorm - 如何让 JetBrains Rider 显示左括号线?
- c# - 转换 IEnumerable
加倍 - tkinter - 多帧中的 Tkinter 网格和 ttk 小部件的潜在影响
- python - 如果 Python 有其他问题,我该如何解决?