0

Lets say I have two different classes with a different number of arguments:

class A(object):
    def __init__(self, arg1, arg2, arg3)
    ...

class B (object):
    def __init__(self, arg1, arg2)
    ....

Is there a way to dynamically instantiate these classes, given there's a difference in the number of arguments?

I'll give you the bigger picture here. I've created a XML parser that has successfully parsed all info from an XML document and cached them into a list, based on tag names (<room> will go into self.room, <item> will go into self.item, etc...)

I don't know if this actually the way of doing things, but what I'm trying to do is take all the info from each individual XML element in their respected list, create Python objects from that info, then store 'em into a dict.

# From XMLParser class
def objectify(self, iterator):
    dict = {}
    # I used elementtree to parse XML documents, 2nd argument of getattr
    # ends up being a capitalized string of iterator's tag name.
    # Ex, <room> becomes 'Room'
    Object = getattr(sys.modules[__name__], iterator.tag.capitalize())
    for element in iterator:
        dict[element.attrib['id']] = Object(...)

So how do i enter the different amount of arguments when dynamically instantiating the different classes, listed above?

Am I anywhere near the right track, or not?

1
  • Use apply (it takes a tuple of arguments and a dictionary of keyword arguments, and calls a function) Commented Jan 26, 2013 at 17:30

2 Answers 2

1

This should be easy:

klass = A
args = (a, b, c)
obj = klass(*args)

You can put all this into a factory function or class.

Sign up to request clarification or add additional context in comments.

2 Comments

It would, but if you know you are calling A, then you don't need to pass a tuple of (in theory) unknown size as the argument.
@WaleedKhan: The OP asker for dynamic instantiation, so I assume he does not know the class a priori. This is a typical use case for the factory pattern.
0

I think *args is your friend here. It represents a list of arguments so can cope with the creation of both classes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.