Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code explain Python Class keyword argparse with Namespace

I have given a task to solve and understand Python OOP concept.
In following code I did not understand what is the purpose of this following line?

user.args = argparse.Namespace(**data)

And how do I access keyword arguments in User class method displayUser, because object of User class is already created before passing the argument. This is what I thought.

Can anyone explain the following code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import argparse 


class User(object):
   
    def __init__(self):
        pass

    def displayUser(self):
        pass



if __name__ == "__main__":

    data = {
        "val_1": "John",
        "val_2": "Doe",
    }

    user = User()
    user.args = argparse.Namespace(**data)

>Solution :

I think what you want to do is something like this:

def displayUser(self):
    print(f"Firstname: {self.args.val_1}, last name: {self.args.val_2}")

You can directly access the val_1 and val_2 from the Namespace object that you set to user.args. In python you can set fields of an object despite them not being defined in the constructor, whether this is a nice approach is a totally different question (it is not, imho).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading