当一个字典时,lambda函数如何返回相同的结果

时间:2017-02-24 10:10:50

标签: python dictionary lambda

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_nameget_name2分配给b1 ... b3,而不幸的是a.apps ,当三个b对象调用get_nameget_name2时,它们都返回“333”,我不明白......

0 个答案:

没有答案