Htom
Htom

Reputation: 21

Python modify instance attribute with instance method

I am trying to use an instance method to modify one of the instance's attribute like this:

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

However, my IDE flags the line self.lr = new_lr as not being ideal coding practice, with the warning Instance attribute lr defined outside __init__. What is the best way to do what I am trying to do with this instance method?

Upvotes: 0

Views: 922

Answers (1)

Pandit Biradar
Pandit Biradar

Reputation: 1877

Try the below code , you need to define the lr in init method and access that any other methods.

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

Upvotes: 1

Related Questions