Python: cómo crear automáticamente una instancia en otra clase

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__ función, algo como esto:

    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' y 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?

preguntado el 27 de noviembre de 13 a las 01:11

In Python 2, shouldn't your classes extend object? -

What exactly are you trying to do? I'm pretty sure there's a way to do what you want that doesn't involve this structure. -

Seems like an XY problem - why do you have the requirement to assign the instance to a specific name? And right now you're trying to create it as a local variable, which makes little sense as it's only accessible in the local scope. What's your use case? -

This still does not work when I add exec 'global '+instancename, which should make it accessible as a global variable. -

My purpose in this is to be able to create an instance of Class1 from one of Class2 while also being able to create an instance without using Class2, and this is the only way I know of to do this. -

1 Respuestas

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

respondido 27 nov., 13:01

Esto, setattr(self,instanceName,class1('attribute text')) does seem to work, making instanceName a global instance of class1. - m.baxter

Though this worked in the example I gave, I got the same error message NameError: name 'instance2' is not defined when I incorporated this into the more complex program I was originally working on. - m.baxter

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.