GLOBAL variables in python

Alex Martelli aleaxit at yahoo.com
Tue Nov 7 09:15:57 EST 2000


<python9999 at my-deja.com> wrote in message
news:8u8qg4$7ps$1 at nnrp1.deja.com...
> i have wriiten a small application in which i need to use the variable
> which is local to one of the functions in a class , but i am not able to
> access the variable.

No, it's not that.


> class myclass:
>     def entry():
>         entry1=GtkEntry(10)
>         entry2=GtkEntry(10)
> ......

This is invalid code.  Any method defined within a
class must have at least one argument -- the first
argument, usually by convention named self, is
the object on which the method will be called.


> a= myclass()
>
> def  get():
>     name=a.entry.entry1.get_text()
>     return name
>
> here i am getting a error like
> name=a.entry.entry1.get_text()
> attribute error entry1

which tells you: a has been located all-right, no
problem whatsoever; neither have there been any
problems with the attribute of a that is named
'entry'; however, 'a.entry' has no attribute
called 'entry1'.  And, indeed, it doesn't;
a.entry is a bound-method object, its attribute
are quite otherwise (for sure they're not named
as the local variables that the method sets...).


> can any one suggest solution for this problem..

It's a bit hard to say what you're trying to do,
and this issue has nothing to do with global
variables.

Perhaps (but not knowing what you try to accomplish,
it's HARD to be sure!-) you mean something like:

class myclass:
    def entry(self):
        self.entry1 = GtkEntry(10)
        self.entry2 = GtkEntry(10)
        ...
        return self

a = myclass()

def get():
    name=a.entry().entry1.get_text()
    return name


Note the differences: method 'entry' now has the
first-argument it needs, and it sets attributes
to the object on which it's called rather than
setting local variables as it did before -- it
also returns the same object on which it was called
so that chaining (as you seem to want to do) is
feasible.

Function get now *calls* the method 'entry' of
a (rather than just *mentioning* it).

However, if get() was called twice, a totally
new value would be set each time for a.entry1
[by method a.entry()] which does not seem very
sensible.  But I'm not going to try any further
to read your mind to try and understand what
exactly it is that you require.


> and i also have a doubt whether v have any GLOBAL variables in python??

Sure, though we don't normally SHOUT them out in
all-caps:-).  They're module-global -- different
modules don't share them except by explicit import
(or, one _can_ set something among the builtins,
but it's rightly considered very bad practice).


Alex






More information about the Python-list mailing list