I'm tasked to make a "Set" class that contains the variable self.list and be able to print and str() the object by writing the __repr__
and __str__
methods. A second file (driver1.py), a "driver file" creates a Set object and attempts to call print(str(set_object)) and print(set_object) but both calls only print a memory address, Set.Set instance at 0x1033d1488>
or some other location. How do I change this? I want it to print out the contents of the set_object in the form {1,2,3}
Here is my code in it's entirety after updating indentation.
class Set:
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
Why do I get the error:
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