[Tutor] How can I access a variable outside a class definition?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Sep 29 23:51:56 CEST 2001


On Sat, 29 Sep 2001, A wrote:

> 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

Side note: I'm a little unfamiliar with this definition of complex
numbers.  Can you explain a little more what this class represents?


> ###########################
> ###########################
> 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?

It's possible for Outside to call methods of Complex, as long as you give
Outside an instance of that Complex class.


Here's an example that might help:

###
class EchoEcho:
    """An EchoEcho person always repeats the same thing."""
    def __init__(self, what_to_say):
        self.what_to_say = what_to_say

    def speak(self):
        return self.what_to_say


def reverse(s):
    """Reverses a string."""
    s_as_list = list(s)
    s_as_list.reverse()
    return ''.join(s_as_list)


class Esrever:
    """An Esrever is someone who listens to a target, and reverses
    whatever that person says..."""
    def __init__(self, mimiced_target):
        self.mimiced_target = mimiced_target

    def speak(self):
        """We get our target to say something, and then we reverse
        whatever they say."""
        speech = self.mimiced_target.speak()
        return reverse(speech)
###



Let's take a look at how this works:

###
>>> jane = EchoEcho("Hi, I'm Jane.")
>>> jane.speak()
"Hi, I'm Jane."
>>> john = Esrever(jane)
>>> john.speak()
".enaJ m'I ,iH"
###


So as long as the "outside" can hold onto an instance of your class, it
can call all of its methods too.

Please feel free to ask more questions on this; OOP programming isn't too
hard, but it does have some concepts that take getting used to.  Hope this
helps!





More information about the Python-list mailing list