Python:如何引用一个实例名? [英] Python: how to refer to an instance name?
问题描述
我正在使用以下代码收集实例:
I'm collecting instances using the following code:
class Hand():
instances = []
def __init__(self):
Hand.instances.append(self)
self.value = 5
def do_something(self, a):
self.value = self.value * a
class Foo():
def __init__(self):
pass
def insty(self):
self.hand1 = Hand()
self.hand2 = Hand()
foo = Foo()
foo.insty()
print Hand.instances
for hand in Hand.instances:
print "how do I print the instance name?"
最后一行只是一种方法来学习如何访问实例名称,
The last line is just a way to learn how to to access the instance name so i can call the 'do_something' method on each instance in order.
如何访问每个实例的实例名称?
How do I access the instance name for each instance of Hand?
推荐答案
如果你想要从你分配给 self.hand1 的实例中获取
hand1
code>,答案是你不能。当你执行 self.hand1 = Hand()
时,你告诉Foo对象它有一个Hand,但Hand对象不知道它已被分配给一个Foo。您可以这样做:
If you mean how to get hand1
from the instance you assigned to self.hand1
, the answer is that you can't. When you do self.hand1 = Hand()
, you tell the Foo object it has a Hand, but the Hand object has no knowledge that it has been assigned to a Foo. You could do this:
h = Hand()
self.bob = h
self.larry = h
现在手的名字是什么?你为bob和larry分配了同一只手,所以没有办法得到一个唯一的名字。
Now what is the "name" of that Hand supposed to be? You assigned the same hand to both "bob" and "larry", so there's no way it can have a single unique name.
如果你想要一个名字每一只手,你需要告诉手什么名字你想给它。你必须修改你的Hand代码,以允许你传递一个名字给构造函数,然后用 Hand(some name)
创建Hand。
If you want to have a name for each hand, you need to tell the hand what name you want to give it. You would have to modify your Hand code to allow you to pass a name to the constructor, then create the Hand with Hand("some name")
.
您当然可以通过为其指定属性来赋予手名称:
You can of course give the hands "names" by assigning attributes on them:
self.hand1 = Hand()
self.hand1.name = "hand 1"
。 。 。但这些名称不以任何方式特殊或自动。
. . . but these names are not special or "automatic" in any way.
底线是,如果你想要某个名称, >需要决定如何处理这个名字。你需要编写自己的代码,给它它的名字,和你自己的代码,检索它的名字。
The bottom line is that if you want something to have a name, you need to decide how to handle that name. You need write your own code that gives it its name, and your own code that retrieves its name.
这篇关于Python:如何引用一个实例名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!