Python在使用时打印内存地址而不是列表

我的任务是创建一个包含变量self.list的“Set”类,并通过编写__repr____str__方法来打印和str()该对象。 第二个文件(driver1.py),一个“驱动程序文件”创建一个Set对象并尝试调用print(str(set_object))和print(set_object),但这两个调用都只打印一个内存地址, Set.Set instance at 0x1033d1488>或其他某个位置。 我该如何改变这一点? 我希望它以{1,2,3}格式打印出set_object的内容

更新缩进后,这是我的代码。

课程设置:

def __init__(self):
    self.list = []

def add_element(self, integer):
    if integer not in self.list:
        self.list.append(integer)

def remove_element(self, integer):
    while integer in self.list: self.list.remove(integer)

def remove_all(self):
    self.list = []

def has_element(self, x):
    while x in self.list: return True
    return False
#probably doesnt work, __repr__
def __repr__(self):
    if self.list.len == 0:
        return "{}"
    return "{"+", ".join(str(e) for e in self.list) +"}"
#Same as above, probably doesnt work
def __str__(self):
    if len(self.list) == 0:
        return "{}"
    return "{"+", ".join(str(e) for e in self.list) +"}"

def __add__(self, other):
    counter = 0
    while counter <= len(other.list):
        if other.list[counter] not in self.list:
            self.list.append(other.list[counter])
        counter = counter + 1

为什么我会收到错误:

 Traceback (most recent call last):
  File "driver1.py", line 1, in <module>
    from Set import *
  File "/Users/josh/Documents/Set.py", line 23
    return "{"+", ".join(str(e) for e in self.list) +"}"
                                                       ^
IndentationError: unindent does not match any outer indentation level

你已经混合了制表符和空格。 不要那样做; 这是你做什么时发生的事情。 Python认为你的一些方法实际上是其他方法的一部分,所以Set类实际上并没有__str____repr__方法。

修复你的缩进,你的问题就会消失。 为了避免将来出现这些问题,请在您的编辑器中打开“显示空白”,如果您认为您可能会看到与选项卡相关的错误,请尝试使用-tt命令行选项运行Python。


还有一个问题:

if self.list.len == 0:

你可能打算这样做:

if len(self.list) == 0:

一旦解决了这个问题,代码将起作用:

s = Set()
s.add_element(1)
s.add_element(1)
s.add_element(2)
s.add_element(3)
print s  # prints {1, 2, 3}
链接地址: http://www.djcxy.com/p/28309.html

上一篇: Python prints memory address instead of a list when using

下一篇: Output difference between ipython and python