0

In the below Python code, I am trying to call the nested function (at step2) independently but getting an 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     

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would like to run step1 and step2 via Tkinter buttons. root=tkinter.Tk() root.title("test") root.geometry("400x300") b=Button(root,text='step1',bg='green',command=Parent,fg='red',width=10,height=3,font=('Times new Roman',20)) b.grid(column=4,row=5) d=Button(root,text='step2',bg='green',command=Parent.child,fg='red',width=10,height=3,font=('Times new Roman',20)) d.grid(column=4,row=6) root.mainloop() but it fails when i click on step2,if i use instance it will rerun parent and creates new value for p1. how can i call child function using previos value of p1
Sounds like you should move the p1 assignment out of __init__ and into a separate method. The class would then either call that method separately when you call child, or raise an error if it hasn't been called first. You'd initialize an instance before the first button definition, and pass its methods as callbacks for the respective buttons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.