懒加载、self.a和_a

//
//  ViewController.m
//  LazyLoading
//

//查看:http://www.jianshu.com/p/417d3a25aaf4

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong) NSArray * personArray;
@end

@implementation ViewController

// 重写getter方法


//使用懒加载的好处:
//
//(1)不必将创建对象的代码全部写在viewDidLoad方法中,代码的可读性更强
//
//(2)每个控件的getter方法中分别负责各自的实例化处理,代码彼此之间的独立性强,松耦合
//

//第一部分:self.personArray是一个getter
//第二部分:不能写成 !self.personArray 这也是一个getter,getter中有getter会造成死循环
//第三部分:可以使用self.personArray,这是一个setter
//第四部分:不能使用self.personArray,这也是一个getter,getter中再有getter,自己引用自己造成死循环
-(NSArray *)personArray{  // 1
    if (!_personArray) {  // 2
        _personArray = [NSArray arrayWithObjects:@"1", nil];   // 3
    }
    return _personArray;    // 4
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 懒加载时需要注意的是当第一次使用对象时,需要调用self.因为只有这样才能调用对应的getter⽅法,对象才会被创建
    NSLog(@"%ld", _personArray.count);  // count: 0
    NSLog(@"%ld", self.personArray.count);  // count: 1
}


@end
把以下代码改写成最新写法class ImageDataset(Dataset): def __init__(self, root, transforms_=None, unaligned=False, mode="train"):# 初始化数据集参数:根目录路径、预处理变换组合、是否非对齐模式、数据集模式(训练/验证等) self.transform = transforms.Compose(transforms_)# 将多个数据增强操作组合成序列 self.unaligned = unaligned # 设置是否使用非对齐图像对(用于CycleGAN等模型) self.files_A = sorted(glob.glob(os.path.join(root, "%s/A" % mode) + "/*.*")) # 使用glob模块递归查找指定路径下所有文件,按文件名排序后获取A类图像文件列表 self.files_B = sorted(glob.glob(os.path.join(root, "%s/B" % mode) + "/*.*")) # 同理获取B类图像文件列表,路径中的%s会被mode参数替换(如train/val) def __getitem__(self, index):# 这是定义如何获取数据集中单个样本的方法。index参数用于指定获取第几个样本 image_A = Image.open(self.files_A[index % len(self.files_A)])#使用循环索引加载A类图像,确保当index超过文件数量时,能够循环到文件列表的开头。 if self.unaligned: #检查是否启用未对齐模式。如果启用,则从B类文件中随机选择一个图像。 image_B = Image.open(self.files_B[random.randint(0, len(self.files_B) - 1)])#在未对齐模式下,随机选择一个B类图像,打破图像对的对应关系。 else: image_B = Image.open(self.files_B[index % len(self.files_B)])#在对齐模式下,按相同索引加载B类图像,保持图像对的对应关系。 # Convert grayscale images to rgb if image_A.mode != "RGB": image_A = to_rgb(image_A)#检查A类图像是否为RGB格式,如果不是,则转换为RGB格式 if image_B.mode != "RGB": image_B = to_rgb(image_B)#检查B类图像是否为RGB格式,如果不是,则转换为RGB格式 item_A = self.transform(image_A)#对A类图像应用预处理变换,如随机裁剪、颜色抖动等。 item_B = self.transform(image_B)#对B类图像应用相同的预处理变换 return {"A": item_A, "B": item_B}#返回包含两个处理后的图像的字典,供DataLoader加载。 def __len__(self): return max(len(self.files_A), len(self.files_B))# 返回数据集长度(取A/B类文件中较大的数量,确保完整遍历所有图像)
最新发布
03-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值