我有两个类(A.py和B.py)定义如下
class AA():
def __init__(self):
self.myvar="MSG from AA"
def getvarA(self):
return self.myvar
def setvarA(self,val):
self.myvar = varimport A as a
class BB():
def __init__(self):
self.e = a.AA()
def setvarB(self,msg):
self.e.setvarA(msg)在我的jupyter笔记本上
import A as a
import B as b
va=a.AA()
vb=b.BB()
print(va.getvarA()) # print MSG from AA as expected
vb.setvarB('new msg')
print(va.getvarA()) # still print MSG from AA and I would like to have 'new msg'我如何使用B方法更新va (我从我的笔记本中知道做va.setvarA('new msg')就是在做这个工作)?
发布于 2020-12-19 09:39:19
va=a.AA()创建AA()的一个实例,vb=b.BB()在BB()中创建一个新的AA()实例,因此当您执行vb.setvarB操作时,它会设置实例self.e的msg,而不是va。要使用BB更新AA的实例,AA的实例需要在BB中。所以你可以做vb=b.BB()和va=vb.e
发布于 2020-12-19 09:47:02
在您的代码中,vb与va没有关系。您无法对将更改va的vb执行任何合理的操作,因为vb不了解va。
您需要向vb提供va,以便它可以对其进行操作。这可以通过在创建vb时将其提供给vb的初始化器来简单地完成
class BB():
def __init__(self, existing_aa):
# Use the existing passed-in instance instead of creating a new one
self.e = existing_aa
. . .
va=a.AA()
vb=b.BB(va) # "Tell" vb about va so it can use ithttps://stackoverflow.com/questions/65365812
复制相似问题