在 Python 中自省构造函数 __init__ 的参数

2022-01-21 00:00:00 python oop arguments introspection

问题描述

什么是从 __init__ 中提取参数而不创建新实例的方法.代码示例:

What is a way to extract arguments from __init__ without creating new instance. The code example:

class Super:
    def __init__(self, name):
        self.name = name

我正在寻找类似 Super.__dict__.keys() 类型的解决方案.只是为了检索名称参数信息而不添加任何值.有这样的选择吗?

I am looking something like Super.__dict__.keys()type solution. Just to retrieve name argument information without adding any values. Is there such an option to do that?


解决方案

Python 3.3+ 更新(如 beeb 在评论中)

Update for Python 3.3+ (as pointed out by beeb in the comments)

您可以使用 在 Python 3.3 中引入的 inspect.signature:

You can use inspect.signature introduced in Python 3.3:

class Super:
    def __init__(self, name, kwarg='default'):
        print('instantiated')
        self.name = name

>>> import inspect
>>> inspect.signature(Super.__init__)
<Signature (self, name, kwarg='default')>

原答案如下

您可以使用 inspect

>>> import inspect
>>> inspect.getargspec(Super.__init__)
ArgSpec(args=['self', 'name'], varargs=None, keywords=None, defaults=None)
>>> 

inspect.getargspec 实际上并没有创建 Super 的实例,见下文:

inspect.getargspec doesn't actually create an instance of Super, see below:

import inspect

class Super:
    def __init__(self, name):
        print 'instantiated'
        self.name = name

print inspect.getargspec(Super.__init__)

这个输出:

### Run test.a ###
ArgSpec(args=['self', 'name'], varargs=None, keywords=None, defaults=None)
>>> 

请注意,instantiated 从未被打印出来.

Note that instantiated never got printed.

相关文章