Newbie: global variables inside class

Fredrik Lundh fredrik at pythonware.com
Thu Dec 1 17:05:38 EST 2005


"tjas ni" <fdredk at gmail.com>  wrote:

> I just got a simple question which I did not find (I bet it's there
> somewhere) in the documentation:
> How can I make a variable access-able globally inside a class?
>
> Like I've got a variable in function 1 which I want to access in function 2.
> Both functions in same class...

assuming class means class instance, and function means method,

    class MyClass:

        def function1(self):
            self.variable = 1 # assign to it

        def function2(self):
            print self.variable # access it

should do the trick (variables are usually initialized in the __init__
method; see the link below for details); usage:

    >>> c = MyClass()
    >>> c.function1()
    >>> c.function2()
    1

but this is surely explained in the documentation:

    http://docs.python.org/tut/node11.html

so you probably meant something else.

</F>






More information about the Python-list mailing list