Python prints memory address instead of a list when using
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
You've mixed tabs and spaces. Don't do that; this is what happens when you do. Python thinks some of your methods are actually internal to some of your other methods, so the Set
class doesn't actually have __str__
or __repr__
methods.
Fix your indentation, and your problem will go away. To avoid such problems in the future, turn on "show whitespace" in your editor, and try running Python with the -tt
command line option if you think you might be seeing tab-related bugs.
There is another problem at:
if self.list.len == 0:
you probably meant to do:
if len(self.list) == 0:
Once this issue is fixed, the code works:
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/28310.html
上一篇: IPython忽略对象的