Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a global variable from within a class?

Tags:

python

class

I'm trying to declare a global variable from within a class like so:

class myclass:
    global myvar = 'something'

I need it to be accessed outside the class, but I don't want to have to declare it outside the class file. My question is, is this possible? If so, what is the syntax?

like image 482
Adam Avatar asked Apr 09 '12 16:04

Adam


People also ask

Can you have a global variable in a class?

Global variables are not technically allowed in Java. A global variable is one declared at the start of the code and is accessible to all parts of the program. Since Java is object-oriented, everything is part of a class. ... A static variable can be declared, which can be available to all instances of a class.

How do you make a variable global from within a function?

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you declare a global variable in a class C++?

You can declare global—that is, nonlocal—variables by declaring them outside of any function definition. It's usually best to put all global declarations near the beginning of the program, before the first function. A variable is recognized only from the point it is declared, to the end of the file.

How do you define a variable inside a class in Python?

Create Class VariablesA class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.


1 Answers

In your question, you specify "outside the main file". If you didn't mean "outside the class", then this will work to define a module-level variable:

myvar = 'something'

class myclass:
    pass

Then you can do, assuming the class and variable definitions are in a module called mymodule:

import mymodule

myinstance = myclass()
print mymodule.myvar 

Also, in response to your comment on @phihag's answer, you can access myvar unqualified like so:

from mymodule import myvar

print myvar

If you want to just access it shorthand from another file while still defining it in the class:

class myclass:
    myvar = 'something'

then, in the file where you need to access it, assign a reference in the local namespace:

myvar = myclass.myvar

print myvar
like image 177
zigg Avatar answered Oct 01 '22 01:10

zigg