Accessing variables from other functions without using global variables
To make a variable calculated in function A visible in function B, you have three choices:
- make it a global,
- make it an object property, or
- pass it as a parameter when calling B from A.
If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:
function A()
{
var rand_num = calculate_random_number();
B(rand_num);
}
function B(r)
{
use_rand_num(r);
}
Calling a variable in a different function without using global
if you don't want to use a global variable, your best option is just to call bye(hello)
from within hi()
.
def hi():
hello = [1,2,3]
print("hello")
bye(hello)
def bye(hello):
print(hello)
hi()
Access Variable from a different function without creating global variables
Without using Globals you say, then create a third function (bean) which would have var someVar = 20;
local variable and provide getter
and setter
functions to use by others.
var SharedSpace = (function(){ var shared = 20; //initialization return { getShared: function(){ return shared; }, setShared: function(val){ shared = val; } }})();
(function(){ alert(SharedSpace.getShared()); SharedSpace.setShared(500)})();
(function(){ alert(SharedSpace.getShared()); SharedSpace.setShared(400)})();
(function(){ alert(SharedSpace.getShared()); SharedSpace.setShared(10)})();
Access a function variable outside the function without using "global"
You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):
def hi():
# other code...
hi.bye = 42 # Create function attribute.
sigh = 10
hi()
print(hi.bye) # -> 42
Functions are objects in Python and can have arbitrary attributes assigned to them.
If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this
argument to each call to the decorated function.
This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self
— I picked something different to avoid confusion, but like the self
argument, it can be named whatever you wish.
Here's an example of that approach:
def add_this_arg(func):
def wrapped(*args, **kwargs):
return func(wrapped, *args, **kwargs)
return wrapped
@add_this_arg
def hi(this, that):
# other code...
this.bye = 2 * that # Create function attribute.
sigh = 10
hi(21)
print(hi.bye) # -> 42
Note
This doesn't work for class methods. Just use the instance argument, named self
by convention, that's already passed to methods instead of the method's name. You can reference class-level attributes through type(self)
. See Function's attributes when in a class.
Access variable from function to another function
In object oriented programming, different methods (functions) of an object can share common variables using the 'this' keyword. Here in this example I declare a class called 'Context' with two methods 'nameOutside' and 'nameInside'. Then I instantiate an object from the class, storing the reference in the 'context' variable. Finally I call the nameInside() method of that object.
class Context {
nameOutside() {
console.log(this.name);
}
nameInside() {
this.name = "my name";
this.nameOutside();
}
}
let context = new Context();
context.nameInside();
Accessing variables outside method call on an object without making them global (is it possible?)
Myself, I'd keep them in one place, without polluting the scope:
MyObject.prototype.template = function(){
this.params = {all: '', these: '', variables: '', etc: ''}
for (var i=0; i<10; i++){
callback();
}};
MyObject.prototype.myFirstMethod = function(){
var self = this;
this.template(function(){
console.log(self.params);
});
};
Python: Is there a way to access variables from other functions without using 'global'?
Python functions are objects. You can define whatever custom properties you want on them:
def a():
a.test = 123
a()
a.test # => 123
Related Topics
How to Get Only First Character Match With Regex
Convert Time Stamp to Date Inside Angular Expression Like {{New Date(Timestamp)}}
How to Display Loading Message When an Iframe Is Loading
How to Force Update Child Component from Parent Component in Reactjs
How to Select All Textframes in Document, and Retrieve the Text in Adobe Indesign
How to Create Line Breaks in Console.Log() in Node.Js
How to Get Public User All Posts from Instagram, Without Instagram API
How to Access Session Variables and Set Them in JavaScript
How Display Selected Item from Bootstrap 4 Drop-Down Item Menu
Javascript/Regex: Remove Text Between Parentheses
Hierarchical Json from Flat With Parent Id
On Click,Redirect to a New Page and Scroll to a Particular Div on That New Page
How to Get Dynamic Id With Javascript/Jquery from PHP Loop
Onclick Button Get from Database and Display on a Input Field Live
Securityerror: Blocked a Frame With Origin from Accessing a Cross-Origin Frame
Regex to Remove Certain Characters At the Beginning and End of a String