Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找“%uuuu init\uuuu()”的参数或在python中构造对象所需的参数_Python_Python Importlib - Fatal编程技术网

查找“%uuuu init\uuuu()”的参数或在python中构造对象所需的参数

查找“%uuuu init\uuuu()”的参数或在python中构造对象所需的参数,python,python-importlib,Python,Python Importlib,我有这样一个场景:我传递一个文件名,并检查它是否有参数start作为构造函数(如果有),然后我必须创建该类的实例 考虑一个例子,我有一个名为test.py的文件,它有三个类,即a、B、C现在只有类a有start参数,其他类有其他不同的参数或额外的参数 #test.py class A: def __init__(self, start=""): pass class B: def __init__(self, randomKeyword, s

我有这样一个场景:我传递一个文件名,并检查它是否有参数
start
作为构造函数(如果有),然后我必须创建该类的实例

考虑一个例子,我有一个名为
test.py
的文件,它有三个类,即
a、B、C
现在只有类
a
start
参数,其他类有其他不同的参数或额外的参数

#test.py
class A:
    def __init__(self, start=""):
        pass

class B:
    def __init__(self, randomKeyword, start=""):
        pass

class C:
    def __init__(self):
        pass
现在我想编写一个脚本,它将
test.py
作为参数,并创建
a
的实例。到目前为止,我的进步很快

detail = importlib.util.spec_from_file_location('test.py', '/path/to/test.py')
module = importlib.util.module_from_spec(detail)
spec.loader.exec_module(mod)

实际上,我需要编写一个程序,在文件中找到所有类的init参数,并创建一个文件实例,将
start
作为init参数。

正如@deceze所提到的,基于类的init参数实例化类不是一个好主意,因为我们不确定其中有什么。但这是可能的。所以我发布这个答案只是为了让你知道如何做到这一点

#test.py
class A:
    def __init__(self, start=""):
        pass

class B:
    def __init__(self, randomKeyword, start=""):
        pass

class C:
    def __init__(self):
        pass
其中一种可能性是

#init.py
import importlib.util
from inspect import getmembers, isclass, signature

detail = importlib.util.spec_from_file_location('test.py', '/path/to/test.py')
module = importlib.util.module_from_spec(detail)
spec.loader.exec_module(module)

for name, data in getmembers(mod, isclass):
    cls = getattr(mod, name)
    parameter = signature(cls.__init__).parameters.keys()
    # parameter start
    if len(parameter) == 2 and 'start' in parameter:
        object = cls(start="Whatever you want")

当然,这不是最好的方法,所以更多的答案是欢迎的,如果你是在这种情况下考虑@欺骗评论,并定义一个建设者。< / P>这听起来不是一个明智的方法,任何事情,真的…?!你不知道文件包含什么,你也不知道你在实例化什么,你只是在实例化它,因为它碰巧有一个具有特定名称的参数@deceze做Python练习是明智的做法:)@user2357112supportsMonica Yes。是的,我就是这么说的。您正在执行一些未知的用户代码,只是因为它有一个名为“
start
”的参数。如果该文件中有许多不同的类,它们都恰好接受“
start
”,但您不应该使用它们,该怎么办?您基本上在这里定义了一个“接口”,即“命名我应该运行的类的参数”
start
”。作为回报,这意味着该名称不能用于该文件中的任何其他内容,这是一个奇怪的限制。您通常会有一个特定名称的方法/函数/类,如
main
,和/或用户将该名称传递给您的程序。例如,在符号
/path/to/test.py:MyClass.start
或类似的东西中。