使用__repr__ __str__时,Python打印内存地址而不是列表?

时间:2014-09-14 22:21:31

标签: python string memory printing repr

我的任务是做一个" Set"包含变量self.list的类,并且能够通过编写__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

2 个答案:

答案 0 :(得分:2)

您混合了标签和空格。不要这样做;这就是你做的事情。 Python认为你的一些方法实际上是你的其他一些方法的内部方法,所以Set类实际上没有__str____repr__方法。

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

答案 1 :(得分:1)

还有另一个问题:

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}
相关问题