python - 为什么从类实例返回的字符串保持 NoneType 类型,即使 IDLE 说它是一个字符串?

标签 python string instance nonetype

我正在使用一个返回字符串的类实例。

我两次调用这个实例并将返回值收集到一个列表中。然后我尝试使用 .sort() 对这两个字符串进行排序。但是,当我这样做时,它会抛出一个错误,指出类型是(Nonetype - 将其视为对象)。

我确实检查了类型(列表的元素),它返回类型“string”。我不知道发生了什么。基本上在空闲状态下,它说我在列表中有字符串。但是在运行时它会抛出一个错误,指出 NoneType(这些字符串的列表)不可迭代。

这是一个例子:

list_of_strings = [class_method(args), class_method(another_args)] ## this instance returns string

print type(list_of_strings[0])  #prints type 'str'

错误:

list_sorted = list(list_of_strings.sort())
TypeError: 'NoneType' object is not iterable

非常感谢!

乔治

最佳答案

来自 python documentation :

7. The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

使用sorted():

list_sorted = list(sorted(list_of_strings))

关于python - 为什么从类实例返回的字符串保持 NoneType 类型,即使 IDLE 说它是一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16877338/

相关文章:

python - 通过 AJAX 将 Django 表单作为 JSON 发送

python - 带有圆角和阴影 Kivy 的图像

c - 如何在运行时在 C 中存储多个字符串数组?

java - 字符串池内存分配

vba - 如何迭代多个 Word 实例(使用 AccessibleObjectFromWindow)

google-app-engine - 一个 GAE 实例中有多少用户?

Python 字节数组 : Function changes other Instance?

修改字符串的Python函数

Java 替换 "with\"

python - 如何从 kwargs 加载包含 ReferenceField 的 Mongoengine 文档