Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 错误,其中为__str“返回的非字符串”;,但显示输出_Python_String - Fatal编程技术网

Python 错误,其中为__str“返回的非字符串”;,但显示输出

Python 错误,其中为__str“返回的非字符串”;,但显示输出,python,string,Python,String,我在班上有 def __str__(self): print "abc" 当我创建此类的对象a并键入print a时,它会打印abc(正确),但也会给出输出 Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> print a TypeError: __str__ returned non-string (type NoneType) 回溯(最近一次

我在班上有

def __str__(self):
     print "abc"
当我创建此类的对象
a
并键入
print a
时,它会打印
abc
(正确),但也会给出输出

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    print a
TypeError: __str__ returned non-string (type NoneType)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
打印
TypeError:\uuuuu str\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

如何修复它?

\uuu str\uuu
应该返回一个字符串

def __str__(self):
     return "abc"
def __str__(self):
     return "abc"
引述

由str()内置函数和print语句调用 计算对象的“非正式”字符串表示形式。这 与repr()的不同之处在于它不必是有效的Python 表达式:可以使用更方便或简洁的表示 相反返回值必须是字符串对象。


\uuuu str\uuuu
应该返回一个字符串

def __str__(self):
     return "abc"
def __str__(self):
     return "abc"
引述

由str()内置函数和print语句调用 计算对象的“非正式”字符串表示形式。这 与repr()的不同之处在于它不必是有效的Python 表达式:可以使用更方便或简洁的表示 相反返回值必须是字符串对象。


打印值和返回值是有区别的。打印该值将在控制台中显示给用户查看,而返回意味着调用该函数的其他代码可以使用该值。您的
\uuu str\uu
方法应为:


打印值和返回值是有区别的。打印该值将在控制台中显示给用户查看,而返回意味着调用该函数的其他代码可以使用该值。您的
\uuu str\uu
方法应为: