How can I import a variable from another script using python 3?
Example:
I have two scripts that we shall call script_1.py and script_2.py.
script_1.py:
class Calculate():
def addition():
a = 5
b = 2
c = a + b
Q: How can I use this second script (script_2.py) to print the variable c from the script_1.py?
You cannot do this since c is not a global variable and doesn't even seem to exist outside of addition. Even if it does exist outside of your class, then the addition method (which should either be def addition(self) or be declared with #staticmethod decorator by the way) won't change it since it's not declared as a global variable in it.
Script 1
class Calculate():
#staticmethod
def addition():
a = 5
b = 2
c = a + b
return c
Script 2
from script_1 import Calculate
print(Calculate().addition())
Will output the value of c (eg 7).
If you need a global variable (you almost certainly don't) :
Script 1
c = None
class Calculate():
#staticmethod
def addition():
global c
a = 5
b = 2
c = a + b
Script 2
from script_1 import c, Calculate
Calculate().addition()
print(c)
You really shouldn't do this. Global variables can lead to serious problems. Global constants however are usually ok.
Related
What type of declaration is the one indicated in this code
def call_counter(func):
def helper(x):
helper.calls1 += 1 # <== This
return func(x)
helper.calls1 = 0
return helper
#call_counter
def succ(x):
return x + 1
print(succ.calls1)
for i in range(10):
print(succ(i))
print(succ.calls1())
What's the name of this is the first time i see something like this
Functions are just objects in Python, so the same way you can add new attributes to instances of your own classes (and to the classes themselves) you can add them to your functions:
def foo():
pass
class Bar:
pass
bar = Bar()
foo.spam = 1
bar.spam = 2
print(foo.spam) # 1
print(bar.spam) # 2
Generally one wouldn't add new attributes to a function object though, since it can quickly get messy and hard to keep track of.
def change(a):
a=4
print('1:')
c=3
print('Value before changing',c)
change(c)
print('Value after changing',c)
print('2:')
d=6
print('Value before changing',d)
change(d)
print('Value after changing',d)
print('3:')
e=7
print('Value before changing',e)
change(e)
print('Value after changing',e)
I want to change n distinct global variables. Eg: I want to change c,d and e global variables using function by passing it as a argument. How can I do so?
Edit:
My original answer wouldn't have worked. So here's my new answer. First, you'll need a function to get the name of the variable. This can be done with the builtin inspect package like so,
import inspect
def retrieve_name(var):
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
return [var_name for var_name, var_val in callers_local_vars if var_val is var]
Then, you'll need to rewrite your change function to
def change(a):
globals()[a] = 4
And use it in conjunction with the retrieve_name function like so,
change(retrieve_name(x)[0])
Because if you just put the retrieve_name inside change it will always return a.
Below is my original answer:
Tell the function change that a is global. Eg:
def change(a):
global a
a = 4
the global keyword tells the function that there already exists a variable of this name, defined outside the current scope. It is in, what python calls, the global scope (think the outter-most scope of a python file).
>>> def change(a, value=4):
global a
a = value
>>> x = 3
>>> change(x)
# x = 4
I've updated my previous answer so that it should work, but here is an alternative method.
def change(**kwargs):
for name in kwargs:
globals()[name] = 4
x = 3
change(x=x) # whatever follows the '=' sign is redundant in this case
Or, you could do
def change(**kwargs):
globals().update(kwargs)
x = 3
change(x=4) # the global value of 'x' is now 4
I have part of a function I would like to turn into another function. I want this new function to be able to edit the variables in in the parent function. Is this possible in python.
I know in other languages that a class can inherent their parents variables and function. I am wondering if there is something similar to this in python?
check here for scoping then here and here for closures. You are ideally looking for enclosing functions. The variables defined within the enclosing functions are available to the sub-functions as though they were globally defined. Most of these are widely dealt with in other languages.
def m(x,y):
z = 2
j = 4
def n():
return x+y+z+j
return n()
m(3,1)
10
is that what you are looking for !
class Parent:
# two class variables x,y
x = 100
y = 100
def __init__(self):
pass
def sum_from_parent(self):
return self.x+self.y
class Child(Parent):
def __init__(self):
super().__init__() # init super class to create x,y variables
def sum_child(self):
# edit base class variables
x_in_child = Parent.x+20
y_in_child = Parent.y+20
return(x_in_child+y_in_child)
c = Child()
print("sum in parent = ", c.sum_from_parent())
print("sum in child = ", c.sum_child())
answer will be
sum in parent = 200
sum in child = 240
I am trying to call a variable from one function into another by using the command return, without success. This is the example code I have:
def G():
x = 2
y = 3
g = x*y
return g
def H():
r = 2*G(g)
print(r)
return r
H()
When I run the code i receive the following error NameError: name 'g' is not defined
Thanks in advance!
Your function def G(): returns a variable. Therefore, when you call it, you assign a new variable for the returned variable.
Therefore you could use the following code:
def H():
G = G()
r = 2*G
print (r)
You don't need to give this statement:
return r
While you've accepted the answer above, I'd like to take the time to help you learn and clean up your code.
NameError: name 'g' is not defined
You're getting this error because g is a local variable of the function G()
Clean Version:
def multiple_two_numbers():
"""
Multiplies two numbers
Args:
none
Returns:
product : the result of multiplying two numbers
"""
x = 2
y = 3
product = x*y
return product
def main():
result = multiple_two_numbers()
answer = 2 * result
print(answer)
if __name__ == "__main__":
# execute only if run as a script
main()
Problems with your code:
Have clear variable and method names. g and G can be quiet confusing to the reader.
Your not using the if __name__ == "__main__":
Your return in H() unnecessary as well as the H() function.
Use docstrings to help make your code more readable.
Questions from the comments:
I have one question what if I had two or more variables in the first
function but I only want to call one of them
Your function can have as many variables as you want. If you want to return more than one variable you can use a dictionary(key,value) List, or Tuple. It all depends on your requirements.
Is it necessary to give different names, a and b, to the new
variables or can I use the same x and g?
Absolutely! Declaring another variable called x or y will cause the previous declaration to be overwritten. This could make it hard to debug and you and readers of your code will be frustrated.
n = 3
d = {'x':n}
d['x'] += 1
print(n)
When I run it, I get
3
How do I make n = 4?
You can't do this, at least, not in any simple way.
The issue is very similar when you're just dealing with two variables bound to the same object. If you rebind one of them with an assignment, you will not see the new value through the other variable:
a = 3
b = a
a += 1 # binds a to a new integer, 4, since integers are immutable
print(b) # prints 3, not 4
One exception is if you are not binding a new value to the variable, but instead modifying a mutable object in-place. For instance, if instead of 1 you has a one-element list [1], you could replace the single value without creating a new list:
a = [3]
b = a
a[0] += 1 # doesn't rebind a, just mutates the list it points to
print(b[0]) # prints 4, since b still points to the same list as a
So, for your dictionary example you could take a similar approach and have n and your dictionary value be a list or other container object that you modify in-place.
Alternatively, you could store the variable name "n" in your dictionary and then rather than replacing it in your other code, you could use for a lookup in the globals dict:
n = 3
d = {"x": "n"} # note, the dictionary value is the string "n", not the variable n's value
globals()[d["x"]] += 1
print(n) # this actually does print 4, as you wanted
This is very awkward, of course, and only works when n is a global variable (you can't use the nominally equivalent call to locals in a function, as modifying the dictionary returned by locals doesn't change the local variables). I would not recommend this approach, but I wanted to show it can be done, if only badly.
You could use a class to contain the data values to enable additions. Basically you are creating a mutable object which acts as an integer.
It is a work around, but lets you accomplish what you want.
Note, that you probably need to override a few more Python operators to get full coverage:
class MyInt(object):
val = 0
def __init__(self,val):
self.val = val
def __iadd__(self,val):
self.val = self.val + val
def __repr__(self):
return repr(self.val)
n = MyInt(3)
print(n)
d = {'x':n}
d['x'] += 1
print(n)