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

Python使用实例方法修改实例属性,python,pytorch,Python,Pytorch,我尝试使用实例方法修改实例的一个属性,如下所示: 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

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

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\u lr行标记为不是理想的编码实践,警告实例属性lr定义在uuu init\uuuuu之外。用这个实例方法做我想做的事情的最好方法是什么

尝试下面的代码,您需要在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

lr应该在uuu init_uuuu中定义,self.lr=None例如是fine只是为了清楚,您不需要这样做,但它被认为是好的样式。