Passing Values Between Class And Instance
class MyClassA(object): def __init__(self): entry = input('Insert a value ::: ') b = MyClassB(entry) #To pass the variable entry to class MyClassB c = M
Solution 1:
The problem you're having is because there are two independent instances of MyClassC
being created, one in MyClassA.__init__()
and a separate one in MyClassB.__init__()
.
The easy way to fix it — not necessarily the best — would be to make MyClassB.__init__()
store the MyClassC
instance it creates in yet another instance attribute, and then refer to the attribute of that object when you want to retrieve the value of p
.
Here's what I mean:
class MyClassA(object):
def __init__(self):
entry = input("Insert a value ::: ")
b = MyClassB(entry) # To pass the variable entry to class MyClassB
####### c = MyClassC() # Initializied MyClassC to be ready for receive the value p
self.x = b.f # To get back the value f from MyClassB
print(self.x)
self.x1 = b.c.p # To get back the value p from MyClassC instance created in MyClassB
print(self.x1)
class MyClassB(object):
def __init__(self, M):
self.f = M * 10 # f will contain (the value entry from MyClassA *10)
self.c = MyClassC(self.f) # Pass variable f to class MyClassC and save instance
class MyClassC(object):
def __init__(self, passedVar):
self.p = passedVar + 0.1 # p will contain (the value entry from MyClassB + 0.1)
h = MyClassA()
Solution 2:
In line
c = MyClassC()
it should be
c = MyClassC(b.f)
Solution 3:
Or you could set the value p
to the class MyClassC
class MyClassC(object):
def __init__(self, passedVar):
MyClassC.p = passedVar + 0.1
but keep in mind that this situation can happen
class T(object):
def __init__(self, x):
T.x = x
if __name__ == '__main__':
t1 = T(3)
print t1.x, T.x
t1.x = 1
print t1.x, T.x
t2 = T(2)
print t1.x, t2.x, T.x
# output:
3 3
1 3
1 2 2
Post a Comment for "Passing Values Between Class And Instance"