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:
classMyClassA(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 MyClassBprint(self.x)
self.x1 = b.c.p # To get back the value p from MyClassC instance created in MyClassBprint(self.x1)
classMyClassB(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 instanceclassMyClassC(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
classMyClassC(object):def__init__(self, passedVar):
MyClassC.p = passedVar + 0.1
but keep in mind that this situation can happen
classT(object):
def__init__(self, x):
T.x = x
if __name__ == '__main__':
t1 = T(3)
print t1.x, T.x
t1.x = 1print t1.x, T.x
t2 = T(2)
print t1.x, t2.x, T.x
# output: 3313122
Post a Comment for "Passing Values Between Class And Instance"