英文:
feed a dictionary-like argument to a class
问题
以下是翻译好的部分:
我正在使用一个需要为我的每个实验(很多实验)构建一个类对象的包,每次都需要将太多的变量传递给这个类。
这个类的源代码如下:
.
.
.
def __init__(self, **kwargs):
keys_to_set = [
'key1',
'key2',
'key3',
.
.
'keyN']
.
.
.
现在,我想为每个实验创建 .csv 文件,并以自动化的方式通过一个字典来传递给这个类,但是字典作为参数对我来说不起作用,会出现错误!
我已经没有了想法,不知道是否有任何“类似字典”的结构可以帮助我。任何帮助/提示都将不胜感激!
为了让情况更清晰一些:
如果我想创建一个像这样的对象 test_obj
:
test_obj = Class(key1=val1,
key2=val2,
.
.
keyN=valN)
是否有办法将参数传递为类似字典的东西,例如:
test_dict = {'key1': val1, ...., 'keyN': valN}
test_obj = Class(test_dict)
(显然,字典不能完成这个任务,我已经测试过了)
英文:
I am using a package where I need to build a class object for each of my experiments (many) and each time I need to feed too many variables into the class.
the class source code looks like:
.
.
.
def __init__(self, **kwargs):
keys_to_set = [
'key1',
'key2',
'key3',
.
.
'keyN']
.
.
.
Now, I want to create .csv files for each experiment, and feed the class through an automated manner e.g. with a dictionary, however dictionary as arguments does not work for me and get errors!
I'm out of ideas, I don't know if there are any "dictionary-like" structures that may help me here. any helps/tips would be appreciated!
to make it a bit clear maybe:
if I want to make an object like test_obj
like this:
test_obj = Class(key1=val1,
key2=val2,
.
.
keyN=valN)
is there any way that I can pass the argument as a dictionary-type thing like:
test_dict = {key1: val1, ...., keyN: valN}
test_obj = Class(test_dict)
(apparently dictionary can not do the job as I have tested)
答案1
得分: 0
我觉得你想要做以下两件事之一:
这样可以创建一个完全基于传递字典的实例。
class Foo():
def __init__(self, data):
for key, value in data.items():
self.__setattr__(key, value)
foo = Foo({"foo": 1, "bar": 2})
print(foo.foo, foo.bar)
或者,这种情况下也可以做同样的事情。
class Foo():
def __init__(self, data):
self.__dict__ = data
foo = Foo({"foo": 1, "bar": 2})
print(foo.foo, foo.bar)
也许,你的构造函数不那么动态,你想基于字典传递键值对。在这种情况下,你可以:
class Bar():
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
bar = Bar(**{"foo": 1, "bar": 2})
print(bar.foo, bar.bar)
所有示例应该得到:
1 2
英文:
I think you are looking to do one of these two things:
This creates an instance based completely on passing a dictionary.
class Foo():
def __init__(self, data):
for key, value in data.items():
self.__setattr__(key, value)
foo = Foo({"foo": 1, "bar": 2})
print(foo.foo, foo.bar)
Alternatively, this does the same in this particular case.
class Foo():
def __init__(self, data):
self.__dict__ = data
foo = Foo({"foo": 1, "bar": 2})
print(foo.foo, foo.bar)
Perhaps though, your constructor is less dynamic and you want to pass it key value pairs based on a dictionary. In that case you might:
class Bar():
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
bar = Bar(**{"foo": 1, "bar": 2})
print(bar.foo, bar.bar)
All examples should result in:
1 2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论