<分区>
我的任务是制作一个包含变量 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