Global variables, Classes, inheritance

Michael Spencer mahs at telcopartners.com
Fri Feb 3 21:10: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.

Use them sparingly IMO

> 
> 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.
> 

Make the dictionary an attribute of the class, not the instance.  Then it will 
be visible by all the instances.  See below:


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

this sets i as an attribute of the class.


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

this probably raises a NameError, unless you happen to have bound 'self' in the 
scope containing Foo, which would be a really bad idea


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

this sets i as an attribute of the instance, self, when it is initialized

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

this assigns the name 'i' in the local scope of the __init__ function.  It has 
no effect on self


So, to get your shared dictionary, you could write:
  >>> class A(object):
  ...     shared_dict = {}
  ...
  >>>
  >>> a1 = A()
  >>> a2 = A()
  >>> a1.shared_dict is a2.shared_dict
  True
  >>> a1.shared_dict["a"] = 42
  >>> a2.shared_dict["a"]
  42
  >>>

Note also, that you create "classic" classes by writing `class Foo:`, and "new 
style" classes by writing `class Foo(object):`.  There are several subtle 
differences between the two, and, since you are just starting, you might as well 
learn with the new ones.

HTH

Michael





More information about the Python-list mailing list