Introspecting arguments from the constructor function __init__ in Python

前端 未结 1 1347
有刺的猬
有刺的猬 2021-02-13 22:56

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

class Super:
    def __init__(self, name):
                


        
1条回答
  •  北海茫月
    2021-02-13 23:40

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

    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__)
    
    

    Original answer below

    You can use inspect

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

    Edit: 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__)
    

    This outputs:

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

    Note that instantiated never got printed.

    0 讨论(0)
提交回复
热议问题