I want to use a class in Python to simulate a 'struct' in C++. Also, I need it in global form as I am using it in many functions and I do not want to pass parameters.
How do I do this(create global objects of a class).
My attempt was :
class MyClass():
//Class Constuctor
global ob1 = Myclass()
def func1():
ob1.name = "Hello World"
def func2():
print(ob1.name)
func1()
func2()
This gives me an 'Invalid Syntax' error, how did I go wrong, or is there a more efficient method to do this?
Note that I have like 10 values, so the class is going to be a pain anyway.
In your code it is not necessary to explicitly place the global modifier, this variable is global by default.
class MyClass():
def __init__(self):
self.name = ""
ob1 = MyClass()
def func1():
ob1.name = "Hello World"
def func2():
print(ob1.name)
func1()
func2()
Output:
Hello World
In addition the use of global is as follows:
global variable
variable = your_value
Related
I want to access the variable number_of_messages in class A but I get "number_of_messages" is not defined error even though I used global keyword. Here is a code sample:
class A:
number_of_messages=0;
def inc(self):
global number_of_messages
number_of_messages+=1
print(A().inc())
Use the class attribute instead:
class A:
def ___init__(self):
self.number_of_messages=0
def inc(self):
self.number_of_messages+=1
a = A()
print(a.inc())
print(a.number_of_messages)
but you can also:
number_of_messages = 0
class A():
def inc(self):
global number_of_messages
number_of_messages+=1
a = A()
a.inc()
print(number_of_messages)
you just forgot to declare the variable in the global scope
That's not a global. That's a class attribute. Write
def inc(self):
A.number_of_messages += 1
You don't need the global statement.
I have three functions that want to change a global variable and can't combine into one function, the way I know right now is keep define "global" keyword in each functions to be able to access global variable. Is there a better way to do the same thing with out keep redefining the global variable? for example:
def fn1(self):
global NUM
NUM = 1
print "fn1 = ", NUM
def fn2(self):
global NUM
NUM = 2
print "fn2 = ", NUM
def fn3(self):
global NUM
NUM = 3
print "fn3 = ", NUM
NUM = 0
fn1(NUM)
fn2(NUM)
fn3(NUM)
Thank you
Why don't you define another function, which changes the value of the global variable with the argument provided as parameter. And call this in rest of your function. For example :
var=None
class A:
def change(self,num):
global var
var = num
def first(self,num):
self.change(num)
def second(self,num):
self.change(num)
def third(self,num):
self.change(num)
a=A()
a.first(1)
print 'value of global variable',var
a.second(2)
print 'value of global variable',var
a.third(3)
print 'value of global variable',var
Otherwise, if the scope of your global variable is supposed to be confined within your class then declare it as a member of the class, and let the functions change it's value. For example :
class A:
def __init__(self):
self.var=None
print "default = ", self.var
def first(self,num):
self.var=num
print "fn1 = ", self.var
def second(self,num):
self.var=num
print "fn2 = ", self.var
def third(self,num):
self.var=num
print "fn3 = ", self.var
a=A()
a.first(1)
print 'value of variable',a.var
a.second(2)
print 'value of variable',a.var
a.third(3)
print 'value of variable',a.va
You can make the global variable a mutable class and then mutate in place.
global_dict = {"data": 1}
global_list = [1]
class MutableInt:
def __init__(self, value=1):
self.value = value
global_int = MutableInt()
This works, but personally I wouldn't call that any better. With the global it is at least 100% clear that you change a global variable. Best would be to change your architecture to not need any global variables.
it seems like the function are part of a class , based on the self keyword , if so they all can access class variable without the need of global keyword, if they are not part of a class you can:
define each function with a given parameter to the function and make that function return a value.
def func1(param_1):
#work on param_1
return param_1
This might seem like a rather weird thing to do, but I was curious if it was possible to implicitly pass a variable down a call chain in Python without passing it as an argument. To better illustrate here is an example:
Here is the "normal" way:
def three(something):
print(something)
def two(something):
# ...
three(something)
def one(something):
# ...
two(something)
And here is what I want to be able to do:
def three():
# something is defined implicitly
print(something)
def two():
# ...
three()
def one(something):
# somehow define something inside a context
# for this activation
two()
For the purpose of this, one, two and three are not in the same class or even the same module.
You don't want to do this.
If you are really convinced that you want to torture yourself, then you could create a separate thread and run the call to one() in that thread. Then just use threading.local for the shared state.
You really don't want to do this.
Here's how you can use thread local storage:
import threading
state = threading.local()
def three():
# something is defined implicitly
print(state.something)
def two():
# ...
three()
def one(something):
# somehow define something inside a context
# for this activation
def inner():
state.something = something
two()
t = threading.Thread(target=inner)
t.start()
t.join()
if __name__=='__main__':
one(42)
one(24)
If you must, you can assign values to the function object itself. Ideally, both three() and two() would perform checks that would raise better exceptions than an AttributeError if 'something' is not set correctly.
def three():
print(three.something)
def two():
three.something = two.something
three()
def one(something):
two.something = something
two()
You could take advantage of lexical closures - define two() and three() within the definition of one().
>>> def one(something):
... def two():
... three()
... def three():
... print something
... two()
...
>>> one(1)
1
You can use __builtins__ to hold your "global variables".
>>> __builtins__.something = "Hello world!"
>>> def foo():
print something
>>> foo()
Hello world!
This can help you avoid passing variables explicitly.
This is a terrible hack. IMHO, you really don't need to do that.
Can I call a function nested inside another function from the global scope in python3.2?
def func1():
def func2():
print("Hello")
return
return
Is ther a way to call func2() from outside func1()?
No, unless you return the function:
def func1():
def func2():
print("Hello")
return func2
innerfunc = func1()
innerfunc()
or even
func1()()
You want to use #larsmans' solution, but theoretically you can cut yourself into the code object of the locally accessible func1 and slice out the code object of func2 and execute that:
#!/usr/bin/env python
def func1():
def func2():
print("Hello")
# => co_consts is a tuple containing the literals used by the bytecode
print(func1.__code__.co_consts)
# => (None, <code object func2 at 0x100430c60, file "/tmp/8457669.py", line 4>)
exec(func1.__code__.co_consts[1])
# => prints 'Hello'
But again, this is nothing for production code.
Note: For a Python 2 version replace __code__ with func_code (and import the print_function from the __future__).
Some further reading:
http://web.archive.org/web/20081122090534/http://pyref.infogami.com/type-code
http://docs.python.org/reference/simple_stmts.html#exec
http://lucumr.pocoo.org/2011/2/1/exec-in-python/
This is based on eyquem's solution.
def func1():
global func2 # put it in global scope
def func2():
print("Hello")
Now you can invoke func2 directly.
But func1() would have to be called before you can call func2() otherwise it will not have been defined yet.
def func1():
def func2():
global fudu
fudu = func2
print("Hello")
func2()
func1()
fudu()
print 'fudu' in dir()
print 'func2' in dir()
result
Hello
Hello
True
False
Also:
def func1():
global func2
def func2():
print("Hello")
func2()
func1()
print 'func2' in dir()
func2()
result
Hello
True
Hello
What's the interest?
I want to do the following in python:
def func1():
var1 = "something"
def func2():
print var1
What is the correct mode to do this ? I've not found in documentation at all
PS. If possible, it's not my plan to make that 'var1' a global variable.
Thanks.
I assume you don't want to pass the variable as a parameter between the function calls. The normal way to share state between functions would be to define a class. It may be overkill for your particular problem, but it lets you have shared state and keep it under control:
class C:
def func1(self):
self.var1 = "something"
def func2(self):
print self.var1
foo = C()
foo.func1()
foo.func2()
No, it is not possible to do things like that. This is because of something called "scope". You can either create a module-level variable or place it in an OOP construct.
Well your func2() is trying to print a variable in the scope of another function. You can either
Return the value of var1 when calling func1 (eg. def func2(): print func1() }
Call func2 from func1 and pass the value of var1
You could try something like
def func1():
var1 = "something"
return var1
def func2():
print func1()
If you need func1 to do more things than just define var1, then maybe what you need is to define a class and create objects? See http://docs.python.org/tutorial/classes.html
You could try:
filename.py:
def func1():
var1 = "something"
def func2():
var = __ import__('filename').var1
print var