Python class 覆盖之前的初始化,而不是创建新的

Python class overwrites previous initialisation, instead of making new ones

老实说,我什至不知道如何调用这个错误。

def create_vimeo_objects_details_DTO_thumbnail(number=5): 
    max_widths = []
    test_thumbnail = []
    for i in range(number):
        new_width = randint(0,2540)
        max_widths.append(new_width)
        dto_thumbnail = {
            'Thumbnail' : {
                'link' : '',
                'width' : new_width
            }
        }
        test_thumbnail = test_thumbnail + [VimeoObjectDetailsDTO(dto_thumbnail).Thumbnail]
    print('test thumbnail: ', [a.width for a in test_thumbnail])

dto_thumbnail 是必须从请求(字典)

启动的 class 的一部分
class VimeoObjectDetailsDTO:

    files = []
    pictures = None
    duration = None

    class FileDto:
        width = None
        height = None
        link = ''
        quality = ''

    class Pictures:
        sizes = []

    class Thumbnail:
        width = None
        link = ''

    def __init__(self, response):
        if 'files' in response: self.files = response['files']
        if 'pictures' in response: self.pictures = response['pictures']
        if 'duration' in response: self.duration = response['duration']
        if 'FileDto' in response:
            if 'width' in response['FileDto']: self.FileDto.width = response['FileDto']['width']
            if 'link' in response['FileDto']: self.FileDto.link = response['FileDto']['link']
            if 'height' in response['FileDto']: self.FileDto.height = response['FileDto']['height']
            if 'quality' in response['FileDto']: self.FileDto.quality = response['FileDto']['quality']
        if 'Pictures' in response:
            if 'sizes' in response['Pictures']: self.Pictures.sizes = response['Pictures']['sizes']
        if 'Thumbnail' in response:
            if 'width' in response['Thumbnail']: self.Thumbnail.width = response['Thumbnail']['width']
            if 'link' in response['Thumbnail']: self.Thumbnail.link = response['Thumbnail']['link']

当我执行这个函数时,我得到例如:

test thumbnail:  [1893, 1893, 1893, 1893, 1893]

但是当我打印 max_widths 时我得到正确的 - 不同的数字

我怎样才能让这个功能 return/print 正确 VimeoObjectDetailsDTO.Thumbnails ? (我用“+”还是追加都无所谓)

您的 classes 的所有实例只有一个 Thumbnail 对象,因为它是一个 class 属性。因此,无论何时你改变 self.Thumbnail,你都会对同一个对象进行操作。

内部 classes 没有那么多合法用途,这当然不是合理的用途。此外,这些 classes 没有任何方法,它们可能是字典,甚至根本不存在,例如 Pictures.

无论如何,无论您做什么,您都希望拥有实例属性,而不是 class 属性,因此您应该在 __init__.

中创建它们