简体   繁体   English

Python:如何在另一个类中自动创建实例

[英]Python: how to automatically create an instance in another class

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: 在编写Python(2.5)程序时,我尝试创建一个类,并在其__init__函数中自动创建另一个类的实例,该类的名称作为__init__函数的参数,如下所示:

    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: 但是,当我创建Class2的实例, instance=Class2('instance2') ,并尝试获取instance2的attribute1(应该已经从Class2的__init__函数创建)时,我收到一条错误消息:

    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. 我不知道问题出在哪里,因为name='instance3'exec name+'=Class1('attribute1')确实可以工作,尽管这可能是因为我对Python没有太多的经验。 How would I be able to do something like this automatically when an instance is created? 创建实例后,我将如何自动执行此类操作?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM