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

标签 python string memory printing repr

<分区>

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

关于Python 在使用 __repr__ __str__ 时打印内存地址而不是列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838577/

相关文章:

python - GitPython 并向 Git 对象发送命令

参数数量可变的Python函数字典

java - 有效地将 Java 字符串转换为表示 C 字符串的以 null 结尾的 byte[]? (ASCII)

memory - 转置数组并实际重新排序内存

c++ - 可以禁用 "Application Error"对话框吗?

python - Django:批量操作

python - 检测常见文件类型

c - 在 C 中查找字符串中的子字符串

python - 为什么引号的类型会改变字符串的值? - Python

c++ - 确定 IWICStream 缓冲区中已用内存的大小