关于Python类的初学者问题
我试图创建一个列表对象,该对象存储整数或字符串并进行排序,但输入也可以是一个列表,即我希望使用=SortedList(5)或=SortedList([7,5,8])创建它关于Python类的初学者问题,python,python-3.x,Python,Python 3.x,我试图创建一个列表对象,该对象存储整数或字符串并进行排序,但输入也可以是一个列表,即我希望使用=SortedList(5)或=SortedList([7,5,8])创建它 当我的对象被实例化时,我得到的只是我的空列表,我的if语句不被考虑。有什么想法吗?您在类型比较方面有问题。您应该将其与int、str和list类型进行比较,而不是与“int”、“str”和“list”字符串进行比较 以下是解决您问题的快速方法: class SortedList: def __init__(self,
当我的对象被实例化时,我得到的只是我的空列表,我的if语句不被考虑。有什么想法吗?您在类型比较方面有问题。您应该将其与
int
、str
和list
类型进行比较,而不是与“int”、“str”和“list”字符串进行比较
以下是解决您问题的快速方法:
class SortedList:
def __init__(self, element):
self.list = []
if type(element) == int or type(element) == str:
self.list = self.list + [element]
if type(element) == list:
self.list = self.list + element
self.list.sort()
a = SortedList(5)
b = SortedList([7, 5, 8])
print(a.list)
print(b.list)
有些事情你可能会做得更好:
list
作为变量名。您可能会意外地覆盖Python的内置列表
类型isinstance
进行类型比较,而不是type(…)==…
isinstance
可以接受类的元组进行比较 class SortedList:
def __init__(self, element):
self.vals = []
if isinstance(element, (int, str)):
self.vals = self.vals + [element]
if isinstance(element, list):
self.vals = self.vals + element
self.vals.sort()
a = SortedList(5)
b = SortedList([7, 5, 8])
print(a.vals)
print(b.vals)
更进一步说,
class SortedList:
def __init__(self, element):
self.vals = element if isinstance(element, list) else [element] # Convert to list if not a list
if not all(isinstance(item, (int, str)) for item in self.vals): # Ensure all items are either ints or strings
raise TypeError("Incorrect Item Datatypes")
self.vals.sort()
a = SortedList(5)
b = SortedList([7, 5, 8])
print(a.vals)
print(b.vals)
c = SortedList([7.0, 5, 8])
Traceback (most recent call last):
File "tester.py", line 16, in <module>
c = SortedList([7.0, 5, 8])
File "tester.py", line 6, in __init__
raise TypeError("Incorrect Item Datatypes")
TypeError: Incorrect Item Datatypes
c=SortedList([7.0,5,8])
回溯(最近一次呼叫最后一次):
文件“tester.py”,第16行,在
c=分类列表([7.0,5,8])
文件“tester.py”,第6行,在_init中__
引发类型错误(“不正确的项目数据类型”)
TypeError:项目数据类型不正确
Python!=Javascript。您正在根据字符串检查类型,但需要使用类型对象,因此type(element)是int
。顺便说一句,请始终使用generic[python]标记标记任何与python相关的问题。在这一点上,Python3基本上被认为是这样的(Python2正在迅速接近它的生命终点),以您不能用list(3)
定义一个单例列表这一事实作为一个巨大的提示,表明您根本不应该这样做。最好使用isinstance()
i.otype()
因为这是进行此类检查的推荐方法,特别是因为该问题是一个初学者问题,详细说明了更多概念以及如何更好地编写代码。请接受您的回答,因为它解决了您的问题:)
c = SortedList([7.0, 5, 8])
Traceback (most recent call last):
File "tester.py", line 16, in <module>
c = SortedList([7.0, 5, 8])
File "tester.py", line 6, in __init__
raise TypeError("Incorrect Item Datatypes")
TypeError: Incorrect Item Datatypes