[Tutor] problem with defining a global class instance
alan.gauld at btinternet.com
Fri Nov 17 10:27:53 CET 2006
"sharath B N" <bn.sharath at gmail.com> wrote
> i am sort of newbie to python. I am trying to do a super Market
> simulation with OOP in python. I have problems with using a class
> instance as global...
> def generate (... ,....,...)
> " in this function i define the global variables "
> global stock,stockManager, manager etc.
Please don't do this!
Global variables are dangerous enough as they are but by
hiding their definitions inside a function you make them
even more difficult to use. The global keyword is really
intended to tell your function to use an existing global
variable not to create new ones (although it does do that
if the variable doesn't exist, its a side-effect that should
be avoided IMHO)
Just declare your global variables in the outer scope of your module:
stock = 0
stockManager = None
manager = 'whatever'
> class Manager
By defining the class here the name is at a global level and
you can create instances as and where you need them.
> def create_stockManager(..)
> """ this is a method in class manager"""
> stockManager = StockManager( name)
> now this gives an attribute error sayin .... stockManager has no
> attribute create_Stock
You need to define the method in your StockManager class
> if i create the StockManager instance in the generate func
> itself...then this problem doesnt come....but i need it this way for
> the program to make sense..
I'm not sure what you mean by the last bit. Are you saying
that if you try to call create_Stock inside the generate function
you don't get an error but if you call it outside you do?
The only reason I can think of for that is that you are actually
defining the class inside the function:
If so that will limit the class definition to inside generate
which you don't want. Simply saying "global stockManager"
in generate doesn't make your class global it just creates
a new name in the global namespace. Another reason not
to try hiding your global data declarations inside the
Author of the Learn to Program web site
More information about the Tutor