Checking for required arguments when instantiating class.

Lacrima Lacrima.Maxim at
Wed May 6 12:08:08 CEST 2009


For example I have two classes:

>>> class First:
	def __init__(self, *args, **kwargs):

>>> class Second:
	def __init__(self, somearg, *args, **kwargs):
		self.somearg = somearg

How can I test that First class takes 1 required argument and Second
class takes no required arguments?
So that I could instantiate them in a for loop.

>>> a = [First, Second]
>>> for cls in a:
	instance = cls()

Traceback (most recent call last):
  File "<pyshell#22>", line 2, in <module>
    instance = cls()
TypeError: __init__() takes at least 2 arguments (1 given)

Of course, I can do like this:
>>> for cls in a:
		instance = cls()
	except TypeError:
		instance = cls('hello')

>>> print instance.somearg

But what if I have to instantiate any class with 3 or 4 required
arguments? How can I do it?

With regards,

More information about the Python-list mailing list