Python类型声明

2024-10-06 10:29:23 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我是python新手,在一本书中找到了这段代码,想试试看,但是第4行说这是一个错误“遇到了一个类型,需要以下一个和一个括号列表。如何修复?在

#: arrays/PythonLists.py

aList = [1, 2, 3, 4, 5]
print type(aList) # <type 'list'>
print aList # [1, 2, 3, 4, 5]
print aList[4] # 5   Basic list indexing
aList.append(6) # lists can be resized
aList += [7, 8] # Add a list to a list
print aList # [1, 2, 3, 4, 5, 6, 7, 8]
aSlice = aList[2:4]
print aSlice # [3, 4]


class MyList(list): # Inherit from list
    # Define a method, 'this' pointer is explicit:
    def getReversed(self):
        reversed = self[:] # Copy list using slices
        reversed.reverse() # Built-in list method
        return reversed 

list2 = MyList(aList) # No 'new' needed for object creation
print type(list2) # <class '__main__.MyList'>
print list2.getReversed() # [8, 7, 6, 5, 4, 3, 2, 1]

#:~

Tags: 代码selftypemethodlistclassprint新手
1条回答
网友
1楼 · 发布于 2024-10-06 10:29:23

您使用的是python3.x,其中print是一个函数,不再是一个语句。这本书是为python2.x编写的,其中print仍然是一个语句。在

您可以使用与本书描述的相匹配的Python版本来修复它,或者获取一本更新版本Python(3.x)的书籍。在

你眼前的问题可以通过写作来解决

print (type(aList))

相关问题 更多 >