Python使用实例方法修改实例属性

问题描述 投票:0回答:1

我正在尝试使用实例方法来修改实例的属性之一,如下所示:

from torch.optim import SGD
from typing import Dict

class ChangeRateSgd(SGD):
    def __init__(self, params, lr: float, lr_change_instructions: Dict):
        super().__init__(params, lr)
        self.lr_change_instructions = lr_change_instructions

    def change_update_rate(self, input_epoch):
        update_mapping = self.lr_change_instructions
        if input_epoch in update_mapping.keys():
            new_lr = self.lr_change_instructions[input_epoch]
            self.lr = new_lr

但是,我的IDE将行self.lr = new_lr标记为不是理想的编码实践,并带有警告Instance attribute lr defined outside __init__。使用此实例方法执行尝试的最佳方法是什么?

python pytorch
1个回答
0
投票

尝试下面的代码,您需要在init方法中定义lr并访问其他任何方法。

from torch.optim import SGD
from typing import Dict

class ChangeRateSgd(SGD):
    def __init__(self, params, lr: float, lr_change_instructions: Dict):
        super().__init__(params, lr)
        self.lr =None
        self.lr_change_instructions = lr_change_instructions

    def change_update_rate(self, input_epoch):
        update_mapping = self.lr_change_instructions
        if input_epoch in update_mapping.keys():
            new_lr = self.lr_change_instructions[input_epoch]
            self.lr = new_lr
© www.soinside.com 2019 - 2024. All rights reserved.