Search code examples
pythonclassattributesinitializer

Get list of attributes required to initialize an object of a class


In Python, Is there a way to get list of attributes required to initialize an object of a class?

For e.g. I have below class:

class MyClass:
  def __init__(self, a, b, c):
    self.a = a
    self.b = b
    self.c = c

And I would like to get,

['a', 'b', 'c'] # These are required to initialize MyClass instance.

may be with the help of,

<something>(MyClass)

Or,

MyClass.<something>

There is a discussion to get list of attributes from an object. List attributes of an object But I would like to know, are there any ways to get list of attributes required to initialize an object?


Solution

  • You can use inspect.getargspecs(YourClass.__init__):

    >>> import inspect
    >>> class Foo(object):
    ...     def __init__(self, a, b, c):
    ...         pass
    ... 
    >>> inspect.getargspec(Foo.__init__)
    ArgSpec(args=['self', 'a', 'b', 'c'], varargs=None, keywords=None, defaults=None)
    

    BUT this won't tell you much about what a, b and c are supposed to be. I suspect a XY problem here, so you should probably explain the problem you're trying to solve with this.