On Tue, 28 Dec 2004 19:34:36 GMT, "It's me" <itsme@yahoo.com> declaimed
the following in comp.lang.python:
[color=blue]
> This must be another newbie gotchas.
>
> Consider the following silly code, let say I have the following in file1.py:
>
> #=============
> import file2
> global myBaseClass[/color]
#1 "global" only applies within a function definition,
where it signals that the subsequent name will be modified within the
function AND exists in the scope external to the function... If the
object name ONLY appears on the right side of an assignment (within the
function), "global" is not needed, as the scope rules will look-up the
external item. However, if the object name appears on the left hand
side, and there is NO "global", Python creates a local object (and will
then complain if you used the name on a right-side before the assignment
creating it).
aGlobalItem = [1, 2, 3]
def aFunction():
global aGlobalItem
aGlobalItem = ('a', 'b', 'c')
return None
Without the "global", the function would create a function-local
called aGlobalItem, and never see the outside object.
[color=blue]
> myBaseClass = file2.BaseClass()
> myBaseClass.AddChild(file2.NextClass())
> #=============
>
> and in file2.py, I have:
>
> #=============
> global myBaseClass
> class BaseClass:
> def __init__(self):
> self.MyChilds = []
> ...
> def AddChild(NewChild):
> self.MyChilds.append(NewChild)
> ...
> class NextClass:
> def __init__(self):
> for eachChild in myBaseClass.MyChilds: # <- ERROR
> ...
> #=============
>
> When I run this, Python complains that myBaseClass is undefined in the last
> line above.
>[/color]
Which is correct. "global" only works within function
definitions /within/ a module (file). To access stuff in other modules
you must "import" the module.
[color=blue]
> What am I doing wrong? (Yes, I know I am thinking too much in C). I
> thought the global declaration would have been sufficient but it's obviously
> not.
>[/color]
#2 You are trying to create a set of recursive
dependencies. File1 is getting an object definition from File2, but
File2 needs the object created in File1...
Terrible design, IMHO...
And why is NextClass a "class"? Does it return a "NextClass"
object?
Either way... I'd probably change the __init__ to take two
arguments: self (which is the NextClass object being created) and 'o'
(the other argument), then use it as
nc = NextClass(myBaseClass)
--[color=blue]
> ================================================== ============ <
>
wlfraed@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
>
wulfraed@dm.net | Bestiaria Support Staff <
> ================================================== ============ <
> Home Page: <http://www.dm.net/~wulfraed/> <
> Overflow Page: <http://wlfraed.home.netcom.com/> <[/color]