Richard Damon 在 2022年8月29日 星期一上午10:47:08 [UTC+8] 的信中寫道: > On 8/27/22 7:42 AM, Mark Bourne wrote: > > Jach Feng wrote: > >> I have two files: test.py and test2.py > >> --test.py-- > >> x = 2 > >> def foo(): > >> print(x) > >> foo() > >> > >> x = 3 > >> foo() > >> > >> --test2.py-- > >> from test import * > >> x = 4 > >> foo() > >> > >> ----- > >> Run test.py under Winows8.1, I get the expected result: > >> e:\MyDocument>py test.py > >> 2 > >> 3 > >> > >> But when run test2.py, the result is not my expected 2,3,4:-( > >> e:\MyDocument>py test2.py > >> 2 > >> 3 > >> 3 > >> > >> What to do? > > > > `from test import *` does not link the names in `test2` to those in > > `test`. It just binds objects bound to names in `test` to the same > > names in `test2`. A bit like doing: > > > > import test > > x = test.x > > foo = test.foo > > del test > > > > Subsequently assigning a different object to `x` in one module does > > not affect the object assigned to `x` in the other module. So `x = 4` > > in `test2.py` does not affect the object assigned to `x` in `test.py` > > - that's still `3`. If you want to do that, you need to import `test` > > and assign to `test.x`, for example: > > > > import test > > test.x = 4 > > test.foo() > > > Yes, fundamental issue is that the statement > > from x import y > > makes a binding in this module to the object CURRECTLY bound to x.y to > the name y, but if x.y gets rebound, this module does not track the changes. > > You can mutate the object x.y and see the changes, but not rebind it. > > If you need to see rebindings, you can't use the "from x import y" form, > or at a minimum do it as: > > > import x > > from x import y > > then later to get rebindings to x.y do a > > y = x.y > > to rebind to the current x.y object. > > -- > Richard Damon Yes, an extra "import x" will solve my problem too! Sometimes I am wondering why "from x import y" hides x? hum...can't figure out the reason:-)
--Jach -- https://mail.python.org/mailman/listinfo/python-list