简体   繁体   English

在 Python 中动态访问类实例“名称”

[英]Access class instance "name" dynamically in Python

In plain english: I am creating class instances dynamically in a for loop, the class then defines a few attributes for the instance.简单地说:我在 for 循环中动态创建类实例,然后该类为该实例定义了一些属性。 I need to later be able to look up those values in another for loop.我稍后需要能够在另一个 for 循环中查找这些值。

Sample code:示例代码:

class A:
    def __init__(self, name, attr):
        self.name=name
        self.attr=attr

names=("a1", "a2", "a3")
x=10
for name in names:
    name=A(name, x)
    x += 1
...
...
...
for name in names:
    print name.attr

How can I create an identifier for these instances so they can be accessed later on by "name"?如何为这些实例创建标识符,以便稍后可以通过“名称”访问它们?

I've figured a way to get this by associating "name" with the memory location:我已经找到了一种通过将“名称”与内存位置相关联来获得此信息的方法:

class A:
    instances=[]
    names=[]
    def __init__(self, name, attr):
        self.name=name
        self.attr=attr
        A.instances.append(self)
        A.names.append(name)

names=("a1", "a2", "a3")
x=10
for name in names:
    name=A(name, x)
    x += 1
...
...
...
for name in names:
    index=A.names.index(name)
    print "name:  " + name
    print "att:  " + str(A.instances[index].att)

This has had me scouring the web for 2 days now, and I have not been able to find an answer.这已经让我在网上搜索了 2 天,但我还没有找到答案。 Maybe I don't know how to ask the question properly, or maybe it can't be done (as many other posts seemed to be suggesting).也许我不知道如何正确提出问题,或者无法完成(正如许多其他帖子似乎暗示的那样)。

Now this 2nd example works, and for now I will use it.现在第二个例子有效,现在我将使用它。 I'm just thinking there has to be an easier way than creating your own makeshift dictionary of index numbers and I'm hoping I didn't waste 2 days looking for an answer that doesn't exist.我只是认为必须有一种比创建自己的临时索引号字典更简单的方法,我希望我没有浪费 2 天时间寻找不存在的答案。 Anyone have anything?有人有什么吗?

Thanks in advance, Andy提前致谢,安迪

Update: A coworker just showed me what he thinks is the simplest way and that is to make an actual dictionary of class instances using the instance "name" as the key.更新:一位同事刚刚向我展示了他认为最简单的方法,即使用实例“名称”作为键制作类实例的实际字典。

Sometimes keeping it simple is best.有时保持简单是最好的。 Having a dict that stores your instances with their names as the keys would be both straightforward and fairly simple to implement.拥有一个 dict 来存储您的实例及其名称作为键将既简单又相当容易实现。

class A:
    instances={}
    def __init__(self, name, attr):
        self.name=name
        self.attr=attr
        A.instances[name] = self

and then to get the proper instance, just...然后要获得正确的实例,只需...

instance = A.instances[name]

No need to put the instance dict inside the class.无需将实例字典放在类中。 Just create a dict, inst in the local scope:只需在本地范围内创建一个 dict, inst

class A:
    def __init__(self, name, attr):
        self.name=name
        self.attr=attr

inst={}
names=("a1", "a2", "a3")
x=10
for name in names:
    inst[name]=A(name, x)
    x += 1

Then, whenever you want to access a certain instance by name, just use inst[name] :然后,每当您想按名称访问某个实例时,只需使用inst[name]

for name in names:
    print inst[name].attr

Yes, the dictionary approach should work well, and can be dovetailed into the class itself.是的,字典方法应该可以很好地工作,并且可以与类本身相吻合。

class A:
    _instances = {}

    @classmethod
    def get(cls, name):
        return A._instances[name]

    def __init__(self, name, attr):
        self.name=name
        self.attr=attr
        A._instances[name] = self

a = A('foo', 10)
aa = A.get('foo')

If you want to play around with __new__ , you can even make this transparent:如果你想玩弄__new__ ,你甚至可以让它透明:

a = A('foo', 10)
aa = A('foo') # 'a' and 'aa' refer to the same instance.

This is a bit complicated, so I'll leave it to you to research (and of course ask another question on SO if you get stuck).这有点复杂,所以我将把它留给你研究(当然,如果你遇到困难,可以再问一个关于 SO 的问题)。

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

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