0

我是 python 的新手,我认为有人问过类似的问题(包括这个问题:你可以使用字符串在 python 中实例化一个类吗?),但我不明白答案或如何应用它们。

我正在尝试使用列表中的“实例名称”来创建一个类的多个实例。

这是我正在尝试做的一个例子:

class InstanceNames():
    def __init__(self):
        self.names = ['inst1', 'inst2', 'inst3']

class DoSomething():
    instances = []
    def __init__(self):
        DoSomething.instances.append(self)

instance_names = InstanceNames()
for x in range(len(instance_names.names)):
    print x
    # following line not working at creating instances of DoSomething
    instance_names.names[x] = DoSomething()

print DoSomething.instances

我更改了循环列表,现在我得到以下输出:

0
1
2
[<__main__.DoSomething instance at 0x10cedc3f8>, <__main__.DoSomething instance at 0x10cedc440>, <__main__.DoSomething instance at 0x10cedc488>]

它起作用了吗?我很困惑,我不确定。

好的。这是一些丑陋的代码,但这是我现在拥有的:

class InstanceNames():
    def __init__(self):
        self.i_names = {'inst1': None, 'inst2': None, 'inst3': None}
        self.o_names = ['foo', 'bar', 'baz']

class DoSomething():
    instances = []
    def __init__(self, blah_blah):
        DoSomething.instances.append(self)
        self.name = blah_blah

    def testy(self, a):
        a = a * 2

instance_names = InstanceNames()

for x in range(len(instance_names.i_names)):
    print x
    instance_names.i_names[x] = DoSomething(instance_names.o_names[x])

print "\n"

print DoSomething.instances

print "\n"

for y in DoSomething.instances:
    print y.name
    print y.testy(4)
    print "\n"

这是我的输出:

0
1
2


[<__main__.DoSomething instance at 0x10dc6c560>, <__main__.DoSomething instance at 0x10dc6c5a8>, <__main__.DoSomething instance at 0x10dc6c5f0>]


foo
None


bar
None


baz
None

为什么'name'变量打印,但'testy'方法不是?

4

5 回答 5

1

您似乎在问“我如何获取字符串'inst1'并创建一个名为'inst1'的变量”。

答案是你不想那样做。相反,创建一个字典或列表,将您的字符串映射到相关对象。有关一些示例,请参见此问题

(如果这不是您要问的,请澄清您的问题。)

于 2012-08-29T06:07:18.960 回答
1

并不是说我不知道​​您真正想要做什么,为了解决您的特定代码,列表只是值的集合。您将其视为一个字典,它是键和值之间的关联。

为了使您的示例正常工作,您将使用 dict:

class InstanceNames():
    def __init__(self):
        self.names = {'inst1': None, 'inst2': None, 'inst3': None}

现在,这将允许以下表达式成功:

instance_names.names[x] = DoSomething()

...因为names现在是一个 dict 并且您正在访问一个键并为其分配一个值。

再次声明,我不知道这段代码试图做什么......感觉它可能不好......但没有从判断它的角度。

于 2012-08-29T06:07:21.203 回答
1

instance_names.names是一个需要数字作为索引的列表。实际上,您发布的 TypeError 也说了同样的话。

但是,您想使用字符串 in 设置元素instance_names.names[x]- wherex是字符串。列表不允许这样做,您需要为此使用字典

有几种方法可以解决您的问题:

  1. 您可以首先为 instance_names.names 使用字典。但是,您必须使用保留对象,None例如尚未创建的实例的占位符:'self.names = {'inst1': None, 'inst2': None, 'inst3': None} , and you must iterate through the keys of the dictionary:for x in instance_names.names.keys():`

  2. 您可以为实例使用单独的字典并在循环中设置其内容:self.instances = {}.instance_names.instances[x] = ...

为了进一步了解 Python 的数据类型,我推荐Dive Into Python

于 2012-08-29T06:15:44.647 回答
1

您可以使用type动态创建类:

type_names = ["Class1", "Class2", "Class3"]
storage = {}
for t in type_names:
    storage[t] = type(t, (object, ), {"your": "instance", "attributes": "here"})

for type_name in storage:
    print type_name, "=>", storage[type_name]

collections.namedtuple或者,如果你真正需要的是一堆属性,你可以用来生成轻量级类。

当前所拥有的是创建该类的三个实例,并将类属性DoSomething中的字符串值(您不使用)替换为.InstanceNamesnamesDoSomething

于 2012-08-29T06:17:20.700 回答
0

这是什么意思or x

self.names范围内不存在,请instance_names.names改用。

于 2012-08-29T06:07:11.657 回答