实例化变量中名为的对象

2024-04-28 08:45:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个组件对象库。我想在另一个对象中包含这些对象的选择的实例。但是我想将该选择作为列表提供,这样每次我用列表实例化容器对象时,它都将用其中指定的子对象创建。你知道吗

假设我的组件库如下所示:

class ColorBlob(object):
    ...
    def wipeItUp()
        ...

class RedBlob(ColorBlob):
    ...
    def paintIt()
        ...
class YellowBlob(ColorBlob):
    ...
    def paintIt()
        ...
class BlueBlob(ColorBlob):
    ...
    def paintIt()
        ...

我的容器对象如下所示:

class Pallet(object):
    def __init__(self, colorList):
        for color in colorList:
            #Ok, here is where I get lost if I know the color I can do this:
            Pallet.BlueBlob = blobLib.BlueBlob()
            #But I don't, so I am trying to do something like this:
            blobSpecs       = getattr(blobLib, color)
            blobSpecs.Obj   = blobSpecs().returnObj(self.page) # with "returnObj" defined in the library as some other method
            setattr(self, Pallet.blobName, blobSpecs) #and I am completely lost.

但我真正想在函数代码中做的是:

workingPallet=Pallet(['RedBlob', 'BlueBlob'])
workingPallet.RedBlob.paintIt()

我知道,当我试图实例化容器中的子对象时,我迷失了方向。有人能帮我理顺我的“getattr”和“setattr”的胡说八道吗?你知道吗


Tags: 对象实例self列表def组件容器class
3条回答

您不能在运行时操作变量名,因为这些变量名仅对编译器可用。解决问题的一个方法是保留一个Map<String, JLabel>(假设您使用的是JLabel而不是其他组件)来将一个名称与每个JLabel关联。我相信还有其他几种可能的解决方案,具体取决于代码的具体设计

无法通过这种方式从String生成“变量”名称。是的,你可以使用反射,但这已经引起了人们对设计质量的质疑

相反。将每个标签放入一个Map中,并按其名称键入

private Map<String, JLabel> labelLookup = new HashMap<>(25); // Instance variable.

在构造器中(或者在构建UI的任何地方),将每个标签添加到Map

/* Other UI code */
labelLookup.put("DummyService1", txt_DummyService1);

现在,当你需要更改时,只需按标签的名称查找标签

// You had better have a VERY good reason for making this static...
public void checker(String services[])
{
    for (String service : services) {
        JLabel label = labelLookup.get(service);
        if (label != null) {
            label.setText("Started");
        }
    }
}

例如

实际上,我在寻找更像下面这样的东西

public static void Checker()
{
    try
    {
        Object Instance = getClass().getDeclaredField("txt_DummyService").get(this);
        Method m = Instance.getClass().getMethod("setText",String.class);
        m.invoke(Instance,"started");
    }
    catch(Exception e)
    {
    //exception handling
    }
}

相关问题 更多 >