【发布时间】:2012-08-26 03:11:43
【问题描述】:
我正在使用以下代码收集实例:
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?"
最后一行只是一种学习如何访问实例名称的方法,因此我可以按顺序在每个实例上调用“do_something”方法。
如何访问 Hand 的每个实例的实例名称?
【问题讨论】:
-
“实例名称”是什么意思?您认为每个实例的“名称”是什么?
-
"hand1" 和 "hand2" 是我所指的......也许是错误的。我是新手……要温柔!
-
for hand in Hand.instances: hand.do_something()有什么问题? -
@dwstein 实例名称只是一个指向一个对象的变量,例如,如果你有,
foo=Foo(),然后是foo1=foo,那么foo和foo1都指向@ 987654327@,那你怎么命名实例呢? -
所以我前几天遇到了这个人……我怎么不能只看他的名字就知道他的名字?你是什么意思意思人们有时有多个名字?