Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global object variable

I want to make use on an object that has been instantinated inside of a class from a standalone module. I am trying to do this by makeing the object reference global. I think I want to make use of the current object and not create a new one.

Assume I have this code in a module file

import moduleFile
class A():
    def checkAdmin(self):
        global adminMenu
        adminMenu = SRMadminMenu()

class SRMadminMenu()
    def createAdminMenu(self):
        pass
        ####Put code to create menu here####

    def createSubMenu(self,MenuText):
        pass
        ####Create a submenu with MenuText####

In moduleFile.py I have this code

def moduleFile_Admin_Menu():
    global adminMenu
    adminMenu.createSubMenu("Module Administration")

the code in moduleFile.py gives me the following error.

NameError: global name 'adminMenu' is not defined
like image 549
PrestonDocks Avatar asked May 12 '13 19:05

PrestonDocks


People also ask

Can Python use global variables?

Global variables can be used by everyone, both inside of functions and outside.

What does global () do in Python?

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

How do you define a global object?

A global object is an object that always exists in the global scope. In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object.

What does global variable mean in Python?

Global Variables In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.


1 Answers

You must declare global variable outside from class.

## Code file something.py
import moduleFile

adminMenu = None

class A():
    def checkAdmin(self):
        global adminMenu
        adminMenu = SRMadminMenu()

then moduleFile.py,

from something import adminMenu

def moduleFile_Admin_Menu():
    global adminMenu
    adminMenu.createSubMenu("Module Administration")

Note: If you will not change adminMenu variable, you don't have to write global adminMenu

like image 80
cengizkrbck Avatar answered Oct 14 '22 17:10

cengizkrbck