Question

In writing a Python (2.5) program, I tried to create a class and, in its __init__ function, automatically create an instance of another class with its name as an argument to the __init__ function, something like this:

    class Class1:
        def __init__(self,attribute):
            self.attribute1=attribute

    class Class2:
        def __init__(self,instanceName):
            #any of Class2's attributes
            exec instanceName + '=Class1('attribute1')'
            # this should produce an instance of Class1 whose name is instanceName

But when I make an instance of Class2, instance=Class2('instance2'), and try to get attribute1 of instance2 (which should have been created from Class2's __init__ function) I get an error message:

    Traceback (most recent call last):
      File "<pyshell#29>", line 1, in <module>
        print instance2.attribute1
    NameError: name 'instance2' is not defined

I don't know what the problem is, since name='instance3' and exec name+'=Class1('attribute1') does work, though this is probably because I don't have much experience with Python. How would I be able to do something like this automatically when an instance is created?

Was it helpful?

Solution

I have to run, so hopefully, someone else can fix any mistakes in this post:

class Class1:
  def __init__(self, attribute):
    self.attribute1 = attribute

class Class2:
  def __init__(self, instanceName):
    setattr(self, instanceName, Class1(...))  # replace ... with whatever parameters you want
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top