datetime.date:TypeError:需要一个整数.为什么?

1 python dictionary class

class Photo:
    'Fields: size, pdate'
    def __init__(self, size, pdate):
        self.size = size
        self.pdate = pdate

def create_photo_name_dict(pdel):
    photo_dictionary = {}
    for photo in pdel:
        photo_dictionary[photo[0]] = Photo(photo[1],datetime.date(photo[2:]).isoformat())
    return photo_dictionary

create_photo_name_dict([["DSC315.JPG",55,2011,11,13],["DSC316.JPG",53,2011,11,12]])
Run Code Online (Sandbox Code Playgroud)

这产生了 TypeError: an integer is required.问题是什么?

aIK*_*Kid 6

datetime.date需要一个整数作为参数.随着photo[2:]你传入片,这是一个列表.因此错误.

要解决此问题,请解压缩列表:

photo_dictionary[photo[0]] = Photo(photo[1],datetime.date(*photo[2:]).isoformat())
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

>>> datetime.date([2010,8, 7])

Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    datetime.date([2010,8, 7])
TypeError: an integer is required
>>> datetime.date(*[2010,8, 7])
datetime.date(2010, 8, 7)
Run Code Online (Sandbox Code Playgroud)