Checking for required arguments when instantiating class.

Lacrima Lacrima.Maxim at gmail.com
Wed May 6 06:08:08 EDT 2009


Hello!

For example I have two classes:

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

>>> 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:
	try:
		instance = cls()
	except TypeError:
		instance = cls('hello')

>>> print instance.somearg
hello

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

With regards,
Max



More information about the Python-list mailing list