0

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?

2 Answers2

1

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

Of course you can:

class MyClass:
    def __init__(self, args):
       self.a = args[0]
       if len(args) > 1:
           self.b = args[1]
       if len(args) > 2:
           self.c = args[2]
mrCarnivore
  • 4,638
  • 2
  • 12
  • 29
  • How does that answer the question exactly ? – bruno desthuilliers Dec 12 '17 at 10:00
  • @brunodesthuilliers: The author requested a possibility to pass a list to a class and use it to init the values. I have provided that... – mrCarnivore Dec 12 '17 at 10:03
  • please re-read the question - what the OP asked for is "how to get (the) list of attributes required to initialize an object of a class" - which actually means (given his example) "how to get the list of arguments expected by a class initializer". – bruno desthuilliers Dec 12 '17 at 10:11
  • Mmh, if you phrase it like that you are right... At first sight is is very ambiguous, though... – mrCarnivore Dec 12 '17 at 10:14