import copy
class B(object):
def __init__(self, name):
self.name = name
class A(object):
def __init__(self):
self.apps = {}
def create_app(self, name):
app = B(name)
if name not in self.apps:
self.apps[name] = app
return app
a = A()
b1 = a.create_app("111")
b2 = a.create_app("222")
b3 = a.create_app("333")
for name, app in a.apps.items():
app.get_name = lambda: name
for name, app in a.apps.items():
new_name = copy.deepcopy(name)
def namegetter():
return new_name
app.get_name2 = namegetter
print(b1.get_name())
print(b2.get_name())
print(b3.get_name())
print(b1.get_name2())
print(b2.get_name2())
print(b3.get_name2())
我定义了A
类和B
类,并将不同的func get_name
和get_name2
分配给b1 ... b3,而不幸的是a.apps ,当三个b对象调用get_name
和get_name2
时,它们都返回“333”,我不明白......