[英]Pass variable to class for use by __init__
I've a class我有一堂课
class Container(ContainerApp):
def __init__(self, config,
image=None,
dns='a.b.c',
image_path=None,
ip=None):
...
It is used in the config of another class as follows:它在另一个类的配置中使用如下:
class BasicTest(TestInterface):
config = {
'timeout': 1000,
'api': MyAPI,
'notification': Container,
}
...
I want to pass an ip
to be used by the Container
class.我想传递一个Container
类使用的ip
。 I tried 'notification': Container(device_ip='1.1.1.1')
in my config but it give me this error:我在我的配置中尝试了'notification': Container(device_ip='1.1.1.1')
但它给了我这个错误:
line 1650, in BasicTest
'notification': Container(ip='1.1.1.1'),
TypeError: __init__() takes at least 2 arguments (2 given)
How do I do this?我该怎么做呢?
It might not be the best solution, but it's doable this way:这可能不是最好的解决方案,但它是可行的:
config = {
'timeout': 1000,
'api': MyAPI,
# 'notification': Container,
}
config['notification'] = Container(config, ip='1.1.1.1')
Assuming that "this" config
(in BasicTest
) is meant to be "that" config
(passed to Container()
) too, and the question is the "recursion".假设“这个” config
(在BasicTest
)也意味着“那个” config
(传递给Container()
),问题是“递归”。
Reading between the lines that you want config['notification']
to be a type instead of an instance, ie that you will later instantiate it yourself, but you want to provide a default value for the ip
parameter already:在两行之间阅读您希望config['notification']
是一个类型而不是一个实例,即您稍后将自己实例化它,但您希望已经为ip
参数提供默认值:
from functools import partial
...
config = {
'notification': partial(Container, ip='1.1.1.1')
}
An alternative would be lambda *args, **kwargs: Container(*args, ip='1.1.1.1', **kwargs)
, which is essentially what partial
papers over very nicely.另一种方法是lambda *args, **kwargs: Container(*args, ip='1.1.1.1', **kwargs)
,这基本上是partial
论文非常好的内容。
In other words, you want config['notification']
to be a callable (eg a function), which, when called, returns an instance of Container
with a predefined value for one of its arguments.换句话说,您希望config['notification']
是一个可调用的(例如一个函数),它在被调用时返回一个Container
的实例,其参数之一具有预定义的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.