Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - How to pass all arguments to self and remove args?

Apologies if the title did not make any sense because I don't know how else to phrase it. I would like to know if there is a way to pass all my arguments args into self and be able to call the arguments in self without typing self.args.

For example, in the following I pass args to self.args but I'll need to type self.args.units if I want to access the variable units.

class model(nn.Module):
    def __init__(self, args):
        super(model, self).__init__()
                
        self.args = args            
        print(self.args.units)

Is there a way for me to call self.units without having to pass args.units to self.units?

print(self.units)

args are the arguments I pass in when calling the program.

parser = argparse.ArgumentParser()
parser.add_argument('--player_attention_type', type=str)
parser.add_argument('--player_velocity_encoder_units', nargs="*", type=int)
args = parser.parse_args()
question from:https://stackoverflow.com/questions/65860286/how-to-pass-all-arguments-to-self-and-remove-args

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will work for an argparse result:

class model(nn.Module):
    def __init__(self, args):
        super(model, self).__init__()

        for key, value in args.__dict__.items():
            setattr(self, key, value)
        print(self.units)

__dict__ is a special property that most objects have. It's the objects attributes (dot properties) expressed as a dict.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...