problem with defining a global class instance

wittempj@hotmail.com martin.witte at gmail.com
Fri Nov 17 02:51:08 EST 2006


sharath B N wrote:
> hi,
> 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.
>
>
> class Manager
> ...
> ...
> ...
> def  create_stockManager(..)
> """ this is a method in class manager"""
> stockManager = StockManager( name)
> stockManager.create_Stock(..)
>
>
> now this gives an attribute error sayin .... stockManager has no
> attribute create_Stock
>
> 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..
> can somebody help me
> thnks
> Sharath

Python uses the concept of namespaces, the keyword 'global' binds a
local variable to the global namespace, take as example:

# this amount is in the global namespace
amount = 98

def get_amount_local():
    # this amount is local in this function
    amount = 23
    return amount

def get_amount_global():
    # this global is taken from the gloabl namespace
    global amount
    return amount

print get_amount_local() # so this will print 23
print get_amount_global() # so this will print 98

see  http://docs.python.org/ref/assignment.html




More information about the Python-list mailing list