cannot declare global vars!

Peter Otten __peter__ at web.de
Thu Sep 13 04:34:17 EDT 2007


Konstantinos Pachopoulos wrote:

> i had posted earlier for not being able to declare global vars. No i 

Post a followup in that thread then rather than starting a new one.

> followed the suggestions and created a class, but still the vars do not
> seem to have a global scope. I have tried pretty much everything. Any
> advice appreciated... Here:

[snip mess]

What Guillaume C. meant is:

To make a variable that is assigned within a function global you have to
declare it global

def foo():
    global x
    x = 42
foo()
print x

but that having many of these globals is a bad design and you should
use instance attributes instead:

class A(object):
    def foo(self):
        self.x = 42
a = A()
a.foo()
print a.x

Personally, I often prefer

def foo():
   return 42
x = foo()
print x

which is both explicit and concise.

These are basic considerations in Python, so I suggest that you read an
introductory text on the language before you proceed with your endeavours.

Peter



More information about the Python-list mailing list