In below Python code, I am trying to call nested function (at step2) independently but getting error. Condition is step1 should execute before step2, this is to ensure that c1 gets the same value of p1
import datetime
def neighbor():
n1 = datetime.datetime.now()
print("n1",n1)
return n1
def parent():
p1 = neighbor()
print("p1",p1)
def child():
nonlocal p1
print("c1",p1)
parent() # step1
child() # step2
CodePudding user response:
The nested function is only available to the function in whose scope you defined it, just like if you declare a local variable inside a function (and indeed, a function is really just a variable whose value is a "callable").
One way to enforce this is to put the definitions in a class.
class Parent:
def __init__(self):
self.p1 = neighbor()
def child(self):
print("c1", self.p1)
Now, you will be able to call the child
method from outside the class
scope, but only when you have created a Parent
object instance. (The __init__
method gets called when you create the instance.)
instance = Parent() # create instance
... # maybe other code here
instance.child()
An additional benefit is that you can have multiple Parent
instances if you want to; each has its own state (the set of attributes and their values, like here the p1
attribute which you access via instance.p1
or inside the class via self.p1
).
Learning object-oriented programming concepts doesn't end here, but this is actually a pretty simple and gentle way to get started.