我想要的是这种行为:
class a:
list = []
x = a()
y = a()
x.list.append(1)
y.list.append(2)
x.list.append(3)
y.list.append(4)
print(x.list) # prints [1, 3]
print(y.list) # prints [2, 4]
Run Code Online (Sandbox Code Playgroud)
当然,我打印时真正发生的是:
print(x.list) # prints [1, 2, 3, 4]
print(y.list) # prints [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
显然,他们正在课堂上分享数据a
.如何获得单独的实例来实现我想要的行为?
所以我有以下代码,其中字典的值是一个对象,该对象的关键是对象中的一个项目:
class MyObject():
def getName(self):
return self.name
def getValue(self):
return self.value
def __init__(self,name, value):
self.name = name
self.value = value
dict = {}
object = MyObject('foo', 2) //foo is the name, 2 is the value
dict[object.getName()] = object
Run Code Online (Sandbox Code Playgroud)
但是我无法像这样访问对象:
>>>print dict['foo'].getValue()
<bound method object.getValue of <__main__.object instance at 0xFOOBAR000 >>
Run Code Online (Sandbox Code Playgroud)
有没有办法以这种方式访问对象?
编辑:
我不知道为什么,但我的代码最终决定开始工作,所以对于任何有类似问题的人,上述代码是有效的,应该可以工作.我当前的Python版本是2.7.3