简体   繁体   English

Python - 从一个 class 获取列表/字典,在另一个 class 中进行修改并将修改值返回给第一个 ZA2F2ED4F8EBC26BBCB1

[英]Python - Get list/dictionary from one class, do the modification in another class and return the modify value to first class

first.py第一个.py

class A():
    lst = [2,2,1]

second.py第二个.py

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.

相关问题 python 从一个 class 获取列表到另一个 - python get list from one class to another Python - 如何从另一个类返回实例的值? - Python - How do I return the value of the instance from another class? 从 python 类返回字典 - Return dictionary from python class 如何在 python 中从一个 class 到另一个 class 获取变量 - How to get variable from one class to another class in python 如何将变量的数据从一个class获取到另一个python中的class? - How to get data of a variable from one class into another class in python? 将列表从另一个类传递到一个类内的方法,以便修改所述列表并传递回Python中的原始类 - Passing a list to a method inside a class from another class in order to modify said list and pass back to the original class in Python 试图弄清楚如何在从字典调用 class 时将变量从一个 class 传递到另一个 python - Trying to figure out how to pass variables from one class to another in python while calling a class from a dictionary 从值python 3中的类的属性获取字典键 - Get dictionary key from attributes of a class in the value python 3 如何将变量值从一个文件中的一个类传递到另一个文件中的另一个类 python tkinter - How to pass variable value from one class in one file to another class in another file python tkinter 无法正确修改 Python class 中的字典 - Can't properly modify dictionary in Python class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM