我有两个班级:ClassA和ClassB
ClassA从ClassB实例化一个实例
有没有办法在ClassB内部访问ClassA实例变量的实际值?
实例变量可能会更改,因此不能将其作为参数提供给ClassB。
class ClassA():
def __init__(self):
self.var_from_A = 1
self.b = ClassB()
class ClassB():
def __init__(self):
# how to get access to self.var_from_A from ClasseA ?
答案 0 :(得分:0)
据我了解,您想访问ClassB中的var_from_A
。就是这种情况,那么您可以执行此操作。我已经将var_from_A作为参数传递给类B。您也可以使var_from_A作为类变量。看到第二个代码
class ClassA():
def __init__(self):
self.var_from_A = 1
self.b = ClassB(self.var_from_A)
class ClassB():
def __init__(self, from_a):
# how to get access to self.var_from_A from ClasseA ?
print("access elem from A {}".format(from_a))
a = ClassA()
使类变量
class ClassA():
var_from_A = 1
def __init__(self):
var_from_A = 1
self.b = ClassB()
class ClassB():
def __init__(self):
# how to get access to self.var_from_A from ClasseA ?
print("access elem from A {}".format(ClassA.var_from_A))
a = ClassA()
答案 1 :(得分:0)
现在,我自己拥有解决方案:第一个类必须将其实例提供给第二个类。因此,第二个类可以访问第一个类中的每个实例对象:
class ClassA():
def __init__(self):
self.var_from_A = 1
self.b = ClassB(self)
def changing_variable(self):
self.var_from_A = 2
self.b.show_variable()
return
class ClassB():
def __init__(self, instance_that_instatiated_me):
self.my_caller = instance_that_instatiated_me
print("access elem from A {}".format(self.my_caller.var_from_A))
def show_variable(self):
print("access elem from A (second time): {}".format(self.my_caller.var_from_A))
return
a = ClassA()
a.changing_variable()