How can I access a variable outside a class definition?
Andrew Walkingshaw
andrew-usenet at lexical.org.uk
Sun Sep 30 22:28:44 EDT 2001
In article <mailman.1001790932.24114.python-list at python.org>, A wrote:
>Hi,
>How can I access a variable defined in one class outside this class
>? For example
>
>I have two classes like below
>
>#############################
>class Complex:
> def __init__(self, realpart1,imagpart1,realpart2,imagpart2):
> self.r1 = realpart1
> self.i1 = imagpart1
> self.r2 = realpart2
> self.i2 = imagpart2
> def Add(self,r1,i1,r2,i2):
> self.sum=self.i1+self.i2
> ImSum=self.sum
> return ImSum
>###########################
>###########################
>class Outside
> def MyFunction(self,ImSum)
> ...
> ...
>
>########################
>
>Is it possible to access,in the Outside class, a value of
>the ImSum
>that was return by
>Add function in that Complex class?
Well, assuming your class definitions above, the following should
clarify things a bit:
MyComp = Complex(1, 2, 3, 4)
MyComp.Add() now won't work, because it takes arguments it doesn't
actually use (for a start); if you're wanting it to add self.i1 and
self.i2, these are part of the self object you're already passing. (In
the above it makes no difference at all what arguments you pass to
MyComp.Add() .)
Hence, you probably actually want
def Add(self)
leaving the rest of that class definition unaltered - or to perform the
add in the __init__ method, as in the example below.
In the second instance, you can just call the method of an instance of
your Complex class:
say,
class Outside:
def __init__(self, someComplexInstance):
self.ImSum = someComplexInstance.Add()
def MyFunction(self):
# use self.ImSum here.
Here is a small example, to which I referred earlier:
class Complex:
def __init__(self, realpart1,imagpart1,realpart2,imagpart2):
self.r1 = realpart1
self.i1 = imagpart1
self.r2 = realpart2
self.i2 = imagpart2
self.imsum=self.i1+self.i2
self.realsum = self.r1+self.r2
def getImSum(self):
return self.imsum
class Outside:
def __init__(self, inst):
self.ImSum = inst.getImSum()
def MyFunction(self):
return self.ImSum
def main():
MyComp = Complex(1,2,3,4)
MyOut = Outside(MyComp)
print MyOut.MyFunction()
if __name__ == '__main__':
main()
Hope this helps,
Andrew
--
"London ice cracks on a seamless line,
We're hanging on for dear life."
- Blur, "For Tomorrow" ('Modern Life is Rubbish')
adw27 at cam.ac.uk (academic) | http://www.lexical.org.uk
More information about the Python-list
mailing list