初始化前获取 class __init__ 个参数

Get class __init__ arguments before initialization

我正在解析文本文件中的参数,我想将它们分配给正确的 classes(以初始化对象)。 现在,我想以一种“聪明”的方式做到这一点,那就是只传递一个参数给 class 如果这个 class 确实可以支持它。

如何在初始化对象之前“询问”class 它接受哪些参数?

这是我想要实现的一些伪代码:

> args_class = Class.magic_get_arguments()
> args_class
['a', 'b']
> args_all_classes # already available
['a', 'b', 'c', 'd']
> args_to_pass_to_class = set(args_class) & set(args_all_classes)
# then use only args_to_pass_to_class when initializing a Class object

我已经尝试查看 class 的 dir 以及 class __init__dir,但参数没有出现在那里。

您可以使用inspect

不清楚您是只需要参数的名称还是还需要类型提示,您可以找到两者。假设 class

class A:
    def __init__(self, arg1, arg2):
        pass

要查找姓名,请执行以下操作:

args_class = list(inspect.signature(A).parameters)
args_class
['arg1', 'arg2']

要查找类型提示以及各种其他信息,您可以遍历参数值:

for arg in inspect.signature(A).parameters.values():
    arg.name # parameter name like before
    arg.annotation # parameter type hint, returns inspect._empty if no type hint exists
    arg.default # returns the default argument for the parameter, or inspect._empty if the parameter has no default
    arg.kind # returns inspect._POSITIONAL_ONLY if parameter is only positional and inspect._POSITIONAL_OR_KEYWORD if argument can be given positionally or by keyword