[英]Passing variable arguments : python
I want to write a code that takes file and class names, and operates over it. 我想编写一个接受文件名和类名并对其进行操作的代码。 An example will explain it much more clearly than I possibly can: 一个例子将比我可能更清楚地解释它:
I have a file test.py
that goes as: 我有一个文件test.py
作为:
import pandas as pd
from preProcess import preProcess
from visualise import visualise
df=pd.read_csv('input.csv')
li1=["preProcess","visualise"]
li2=["minMax","pca"]
for i in range(len(li1)):
x = getattr(getattr(__import__(li1[i]),li1[i]), li2[i])
a=x(df)
# does some more stuff...
li1
contains name of the modules and li2
contains the name of the classes in the corresponding modules. li1
包含模块的名称, li2
包含相应模块中的类的名称。
To make it a bit clearer, preProcess.py
goes as: 为了更清楚一点, preProcess.py
如下:
class minMax():
def __init__(df):
# does something
and visualise.py
goes as: 而visualise.py
如下:
class pca():
def __init__(df):
# does something
The line x = getattr(getattr(__import__(li1[i]),li1[i]), li2[i])
gives me the classes minMax
and pca
. x = getattr(getattr(__import__(li1[i]),li1[i]), li2[i])
给了我minMax
和pca
类。
Now the thing is that this code works perfectly fine if __init__
takes only one argument. 现在的问题是,如果__init__
仅接受一个参数,则此代码可以正常工作。 But, what if it requires more than 1 arguments? 但是,如果需要多个参数,该怎么办? For eg., pca
could have been: 例如, pca
可能是:
class pca():
def __init__(df,metaData):
# does something
What should I do in such a case? 在这种情况下我该怎么办? Any help would be appreciated. 任何帮助,将不胜感激。
If the question is not clear, please drop a comment. 如果问题不清楚,请发表评论。 I would provide a more detailed explanation then. 那我将提供更详细的解释。 Thanks... 谢谢...
perhaps you should utilize the spread operator. 也许您应该利用点差运算符。 maybe this snippet helps: 也许这段代码有帮助:
class X:
def __init__(self, a, b):
self.a = a
self.b = b
args = [2, 'hellow']
x = X(*args)
EDIT : this is just an outline of the general approach. 编辑 :这只是一般方法的概述。 for a more comprehensive overview of how this approach is applicable to this specific problem, please check the discussion on this answer. 有关此方法如何适用于此特定问题的更全面的概述,请检查有关此答案的讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.