Global variables, Classes, inheritance

Kirk McDonald mooquack at suad.org
Fri Feb 3 21:11:53 EST 2006


DaveM wrote:
> Although I've programmed for fun - on and off - since the mid 70's, I'm
> definitely an OO (and specifically Python) beginner. 
> 
> My first question is about global variables. Are they, as I'm starting to
> suspect, a sin against God or just best avoided? Having got my current
> application working using them, I'm not sure whether I want to refactor it,
> but equally, I'd like to write the best code I can.

Python globals are actually remarkably safe, at least compared to some 
other languages. The key is that, when you import a module, its globals 
stay in its namespace. I've got nothing against them.

> 
> Secondly (and this is related),  if you have multiple instances of the same
> class, but need them all to have access to a dictionary created at run-time,
> is there a class way to this without calling the creation method multiple
> times? The best thought I've come up with is for the class instance to check
> its name and only if it's the first one do the dictionary creation, but I
> haven't tried it yet.

A class attribute would do this easily:

class Foo(object):
     d = {}

a = Foo()
b = Foo()
Foo.d = { 'a' : 'apple' }
print a.d
print b.d

That will print out {'a':'apple'} twice.

> 
> My third difficulty is with variables in a class. What's the difference
> between the following?:
> 
> class Foo:
>     i = 12345
>     ...
> 

i is a class attribute. It is bound to the class (which is, itself, an 
object). You can access i both from the class itself as well as from an 
instance of the class, i.e., Foo.i and Foo().i will both work.

> class Foo:
>     self.i = 12345
>     ...
> 

This does not work. There is no name 'self' bound to class Foo.

> class Foo:
>     def __init__(self):
>         self.i = 12345
>         ...
> 

This binds the name 'i' to all instances of class Foo; if this were C++, 
we'd call self.i a member variable.

> class Foo:
>     def __init(self):
>         i = 12345
>         ...
> 

(You forgot the trailing __, but whatever. :-) This binds the name 'i' 
to the local namespace of the __init__ function. It is just like any 
other local variable in a function.

Namespaces in Python are really great. It is worth reading up on 
globals() and locals() if you don't get them yet.

-Kirk McDonald



More information about the Python-list mailing list