Python - 如何打印其中包含类对象的列表内容?

标签 python list class oop object

我是 Python 新手,在这里没有找到类似的先前问题。 我的问题是如何在这里看到列表 node_list 的真实内容,而不是内存地址? (实际上包括node1、node2名称及其邻居)

class node:
  def __init__(self, name):
    self.name=name
    self.neighbors={}

  def update(self, name, weight):
    if name in self.neighbors:
      self.neighbors[name]=max(int(weight),int(self.neighbors[name]))
    elif self.name==str(name):
      print ("this is prohibited to add a key name as an existed name")
    else:
      self.neighbors[name] = str(weight)

node_list = []

node1 = node('1')
node_list.append(node1)
node1.update('2',10)
node1.update('4',20)
node1.update('5',20)

node2 = node('2')
node_list.append(node2)
node2.update('3',5)
node2.update('4',10)

print(node1.name)        #  That's OK - prints:  1
print(node1.neighbors)   #  That's OK - prints:  {'2': '10', '4': '20', '5': '20'}
print(node_list)         #  Not OK: prints:[<__main__.node object at 0x7f572f860860>, <__main__.node object at 0x7f572f860dd8>]  

最佳答案

我认为您必须为类定义中的节点创建一个 __str__ 方法。否则,Python会自动打印内存地址。

这是一个类似的问题。

How to print a class or objects of class using print()?

关于Python - 如何打印其中包含类对象的列表内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51564071/

相关文章:

python - 如何将用户输入分配给变量或列表

python - 按值对字典排序并返回字典,而不是元组列表

python - 装饰类方法以构建方法注册表

c++ - Python 和 C++ 脚本交互

python - Tkinter 如何根据此组合框自动更新第二个组合框

python - MATLAB 和 Python 之间的不同频谱图

python - 在 python 中列出目录时使用通配符

mysql - cakephp 3 使用另一个表中的数据填充列表

java - 如何要求.class参数是Java中的某个类?

c++ - 避开头文件 'pollution'