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?
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).