[英]Code explain Python Class keyword argparse with Namespace
I have given a task to solve and understand Python OOP concept.我给了一个任务来解决和理解 Python OOP 的概念。 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.以及如何在用户class 方法displayUser中访问关键字 arguments ,因为在传递参数之前已经创建了用户ZA2F2ED4F8EBC2CBB1DABC6 的 object 。 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)
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
.您可以从设置为
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).在 python 中,您可以设置 object 的字段,尽管它们没有在构造函数中定义,这是否是一个好的方法是一个完全不同的问题(它不是,恕我直言)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.