[英]Python - Get list/dictionary from one class, do the modification in another class and return the modify value to first class
class A():
lst = [2,2,1]
from first import A
class B():
new_lst = A.lst
new_lst.remove(1)
#new_lst = [2,2]
Now how can i update new_list value from class B to class A so that class A, lst=[2,2]现在我如何将 new_list 值从 class B 更新为 class A 以便 class A, lst=[2,2]
Please help me out.请帮帮我。
I wrote this as a comment at first, but I might as well write a complete answer for it.我一开始是把它写成评论,但我不妨为它写一个完整的答案。 When you call
new_lst = A.lst
you're not actually copying the values inside of A.lst
.当您调用
new_lst = A.lst
时,您实际上并没有复制A.lst
内部的值。 What's happening is that you're creating a pointer to the variable inside of A
.发生的事情是您正在创建一个指向
A
内部变量的指针。
We can demonstrate this by adding a couple of lines inside of second.py :我们可以通过在second.py中添加几行来证明这一点:
from first import A
class B:
new_lst = A.lst
print(f'A: {A.lst}, B: {B.new_lst}') #Output: A: [1, 2, 3], B: [1, 2, 3]
B.new_lst.append("testing")
print(f'A: {A.lst}, B: {B.new_lst}') #Output: A: [1, 2, 3, 'testing'], B: [1, 2, 3, 'testing']
A.lst.remove(3)
print(f'A: {A.lst}, B: {B.new_lst}') #Output: A: [1, 2, 'testing'], B: [1, 2, 'testing']
As you can see, if we add a new variable to B.new_lst
it's also added to A.lst
likewise when we remove a value from A.lst
.如您所见,如果我们向
B.new_lst
添加一个新变量,当我们从A.lst
中删除一个值时,它也会被添加到A.lst
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.