Can functions access variables defined in its own parent function?
The reason why the first example fails and the second 'works' has to do with scope and closure. You can think of a function's 'curly braces' as the enclosure around its scope - or sphere of influence.
The first example fails because myBigFunction()
's variable is not accessible to subFunction1()
's scope. myBigFunction()
also doesn't wrap subFunction1()
which would provide a closure. Check out closures here.
However, add()
is declared within the scope of the getScore()
function. getScore()
'wraps' add()
- providing a closure so that add()
has access to variables within getScore()
's scope.
Access a variable by name defined in a parent function from a nested function
Yes it's possible, but you are working against Python, don't do this:
In [1]: import inspect
In [2]: def f():
...: x = 1
...: def g():
...: print(inspect.currentframe().f_back.f_locals['x'])
...: g()
...:
In [3]: f()
1
Seriously, don't. Write good code, not bad code. For all of us.
Accessing a variable defined in a parent function
PHP<5.3 does not support closures, so you'd have to either pass $foo to inner() or make $foo global from within both outer() and inner() (BAD).
In PHP 5.3, you can do
function outer()
{
$foo = "...";
$inner = function() use ($foo)
{
print $foo;
};
$inner();
}
outer();
outer();
Accessing variables passed to, or defined in, parent R function
The issue is that Foo
is defined in the global environment.
Adding the line
environment(Foo) <- environment()
before calling Foo within Func1
and Func2
produced the desired behaviour.
How to access variable from the parent function in R
you can access the scope of the calling function through the called function's parent frame:
mother <- function(){
year_change = 8
child()
}
child <- function(){
print(parent.frame()$year_change)
}
... or define them in one of the function's immediate parent environments:
mother <- function(){ ## now the immediate parent environment
year_change = 8
child <- function(){
print(year_change)
}
child()
}
... or in the global environment:
year_change = 8 ## the global environment
mother <- function(){
print(paste("mom's idea of year_change is:", year_change))
child <- function(){
print(paste("kid's idea of year_change is:", year_change))
}
child()
}
Note that the immediate parent environment outmatches the farther ancestors if variables have the same name.
Details of scoping e.g. in H. Wickham: Advanced R
Edit
Shamefully forgot the possibility to pass variables through by taking advantage of the ellipsis ...
argument.
example
mother_says <- function(...){
tell_child(...)
}
tell_child <- function(...){
args <- list(...)
print(paste("Mom says:", args$message_to_daughter))
tell_grandchild(...)
}
tell_grandchild <- function(...){
args <- list(...)
print(paste("Granny says:", args$message_to_grandchild))
}
example's output:
## > mother_says(message_to_daughter = "Hi, daughter, how're you?",
## + message_to_grandchild = "Grandchild, sweetie!"
## + )
##
## [1] "Mom says: Hi, daughter, how're you?"
## [1] "Granny says: Grandchild, sweetie!"
Accessing parent function's variable in a child function called in the parent using python
In this case, you'd probably like to use a class. They are really easy to get your head around. Note the self
variable that is passed, and take a look here for a quick explanation of scope in classes.
#!/usr/bin/env python3
class Family(object):
def parent(self):
self.test = 0
self.child()
def child(self):
self.test += 1
print(self.test)
if __name__ == "__main__":
Family().parent()
So, to translate to your code:
#!/usr/bin/env python3
class Graph(object):
def depthFirstSearch(self):
for vertex in self.adjacency_list:
vertex.status = "not visited"
vertex.previous = None
self.visit_count = 0
for vertex in self.adjacency_list:
if vertex.status == "not visited":
self.depthFirstSearchVisit(vertex)
def depthFirstSearchVisit(self, vertex):
self.visit_count += 1
vertex.distance = self.visit_count
vertex.status = "waiting"
for edge in vertex.edges:
if edge.status == "not visited":
edge.previous = vertex
self.depthFirstSearchVisit(edge)
vertex.status = "visited"
self.visit_count += 1
vertex.distance_finished = self.visit_count
class Edge(object):
status = "not vistited"
class Vertex(object):
def __init__(self):
self.edges = [Edge(), Edge()]
if __name__ == "__main__":
graph = Graph()
graph.adjacency_list = [Vertex(), Vertex()]
graph.depthFirstSearch()
Nothing fancy needed.
Related Topics
In PHP, How to Call a Function Interpolated in String
How to Disable Mod_Security in .Htaccess File
How to Access Static Member of a Class
Php, MySQL - Too Many Connections to Database Error
Install Intl PHP Extension Osx High Sierra
How to Send an Email Using PHP at Windows Azure
Laravel Querybuilder How to Use Like in Wherein Function
How to Enable Ssl in Wamp Server
How to Determine Whether It's a Mobile Device with PHP
Doctrine2 Association Mapping with Conditions
How to Send the Values of an Array of Checkboxes Through Ajax Using Jquery
Remove Zero Values from a PHP Array
How to Serve an Image with Laravel
Extending Sonata User Bundle and Adding New Fields
Subtracting a Certain Number of Hours, Days, Months or Years from Date