我似乎犯了一个我找不到的愚蠢错误。我只是试图从记录类中调用我的函数,尽管查看了示例代码并尝试模拟语法,但语法错误仍然无效。
我尝试了以下教程,并以各种方式调用该函数,因此问题可能不在于函数的调用,而是我的其他感受。
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
def addrecord(self,x,y,z):
x = input('Enter telephone number')
y = input('Enter lastname')
z = input('Enter firstname')
phonebook.append(record(x,y,z))
return
def deleterecord(self,x):
phonebook[x-1].pop
return
phonebook = record[]
addrecord(515,'fin','matt')
print(phonebook[0].firstname)
deleterecord(1)
print(phonebook[0].firstname)
如果所有这些都可行,我希望输出为 “哑光” “空”
答案 0 :(得分:0)
您的代码有很多问题:
deleterecord
中,您应该致电phonebook.pop(x)
。 namedtuple
对记录进行建模。record[]
无效的Python。替代实现:
from collections import namedtuple
PhoneRecord = namedtuple("PhoneRecord", ['firstname', 'lastname', 'telephone'])
class PhoneBook:
def __init__(self):
self._phonebook = []
def addrecord(self, record):
self._phonebook.append(record)
return self._phonebook.index(record)
def deleterecord(self, i):
self._phonebook.pop(i)
phonebook = PhoneBook()
record_index = phonebook.addrecord(PhoneRecord(firstname="matt", lastname="snow", telephone="25512521"))
print(phonebook._phonebook)
phonebook.deleterecord(record_index)
print(phonebook._phonebook)
将在控制台中显示:
[PhoneRecord(firstname='matt', lastname='snow', telephone='25512521')]
[]
答案 1 :(得分:0)
问题的简化版本是给定代码
records = []
records.append("matt")
print(records[0])
del records[0]
print(records[0])
为什么我没有得到以下输出
"matt"
None
相反,您会遇到IndexError
异常。
原因是您正在访问超出列表大小的元素,Python通过引发异常而不是不返回None来处理此问题。