为什么我的自定义数据集给出属性错误?

Why is my custom dataset giving attribute error?

我正在尝试创建一个自定义数据集,如果我既不调用 getitem 也不调用 len 函数作为 object.len() 或 object.getitem(index) 我得到这个错误

File ~/Library/Python/3.9/lib/python/site-packages/torch/utils/data/dataset.py:83, in Dataset.__getattr__(self, attribute_name)
     81     return function
     82 else:
---> 83     raise AttributeError

代码本身如下,

class CustomDataset(Dataset):
def __init__(self,
             path_to_images,
             transform_extra=None,
             img_size=128):

    self.images= createimages(path, img_size)

def __len__(self):
    return len(self.images)
    
def __getitem__(self, idx):
    return self.images[idx][0], self.images[idx][1]

Images 是 Pillow 图像和字符串标签的二维列表,createimages 函数在 class 之外工作。我对 Python 不是很熟悉,所以我想知道这里出了什么问题。

这些函数是 python 中特殊函数子集的一部分,通俗地称为“魔法方法”,由前后双下划线表示。 this 的确切含义对于不同的函数略有不同,但通常双下划线是为了将这些函数与其他具有相似名称的函数区分开来,因为它们在 python 中有特殊用途。其他示例包括 __next__()__dir__ 等。请参阅 similar question

cd成为CustomDataset的实例。作为一种特殊性,__len__ 函数被称为 len(cd)(或者您可以 cd.__len__()。)__getitem__ 函数通常被称为 cd[i],其中i 索引作为索引变量传递给 __getitem__,(但同样你可以做 cd.__getitem__())。