1
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())

I defined the A class and B class, and assign two different func get_name and get_name2 to b1...b3 while iter the a.apps, unfortunately, when the three-b objects calling the get_name and get_name2, they're all return "333", I don't figure it out...

Jonatas CD
  • 878
  • 2
  • 10
  • 19
  • `lambda: name` will return the current value of the variable `name` **at the point when the function is called**, not at the point the lambda function is defined. – khelwood Feb 24 '17 at 10:15

0 Answers0