使用datetime类函数产生的错误



我正在python 3中编写一个函数,它使用photo-dir-entry-list (pdel)并生成一个类型为photo-name-dict的字典,其中键是照片的文件名,值是photo类型的对象,字段大小具有photo-dir-entry中元素的大小,字段update具有photo-dir-entry中元素的日期。我写的函数产生了一个错误:

 ## A photo-dir-entry is a list consisting of the following
 ## elements in order:
 ## - a Str representing the filename of the photo
 ## - an Int[>=1] representing the size of the photo file
 ## - an Int representing the year the photo was taken
 ## - an Int[1<=,<=12] representing the month the photo was taken
 ## - an Int[1<=,<=31] representing the day the photo was taken
 ## The Date elements contain a valid date.
 ## A photo-dir-entry-list is a list of photo-dir-entries with unique filenames.
 ## A Photo is an object consisting of two fields
 ## - size: an Int[>0] representing the size of the file
 ## - pdate: a Date representing the date the photo was taken    
 class Photo:
     'Fields: size, pdate'
 ## Purpose: constructor for class Photo
 ## __init__: Int Int Int Int -> Photo
 ## Note: Function definition needs a self parameter and does not require a return statement
def __init__(self, size, year, month, day):
    self.size = size
    self.pdate = date(year, month, day)
 ## Purpose: Produces a string representation of a Photo
 ## __repr__: Photo -> Str
def __repr__(self):
    s1 = "SIZE: " + str(self.size)
    s2 = "; DATE: " + self.pdate.isoformat()
    return s1 + s2
def create_photo_name_dict(pdel):
    ph_dict = {}
    for entry in pdel:
        ph_dict[entry[0]] = Photo(ph_dict[entry[1]], ph_dict[entry[2]],  ph_dict[entry[3]], ph_dict[entry[4]])
    return ph_dict

当我调用函数时:

create_photo_name_dict([["DSC315.JPG",55,2011,11,13],
                        ["DSC316.JPG",53,2011,11,12]])
在我应该输出 的地方出现了错误
{ "DSC315.JPG": Photo(55,2011,11,13),
         "DSC316.JPG": Photo(53,2011,11,12)}

错误是:

`Traceback (most recent call last):
  File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py", line 2, in <module>
if __name__ == '__main__':
  File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py", line 56, in create_photo_name_dict
builtins.KeyError: 55` 

create_photo_name_dict()中,在for循环中创建字典时,您试图将参数传递给Photo作为ph_dict[entry[1]]等。但是ph_dict最初是空的,所以这永远不会工作(而且很确定这也不是你想要的)。

按原样发送entry[1], ' entry[2]等,我相信这也是你想要的-

ph_dict[entry[0]] = Photo(entry[1], entry[2],  entry[3], entry[4])

相关内容

  • 没有找到相关文章

最新更新