How can i print a function contained within another function and called by a third function?

Question:

I would like to print 10, but I get the error: AttributeError: 'function' object has no attribute 'x'

How to fix? Thank you

def function1():
    def x(): 
        a=10
        return a
  
def function2():
    y = function1.x()
    return y

function2()


Asked By: DavidGr92

||

Answers:

You need to return x and call function1 as a function

def function1():
    def x(): 
        a=10
        return a
    return x
  
def function2():
    y = function1()()
    return y

function2()
Answered By: Samathingamajig

Functions are not containers you can reference into – classes, objects, structs or records (depending on your language) provide that, but never functions. All a function can or should do is take parameters, run and return a result.

BTW, one very good reason for this is that functions only have memory for their local values while they’re running (this is called a "stack frame"). A value defined locally within a function does not exist except while that function is running.

Answered By: Edward Peters

You can make use of class as shown below:

class function1(object):
    def x(): 
        a=10
        return a
  
def function2():
    y = function1.x()
    return y


function2()  #works now and returns 10

Working demo

Answered By: Jason Liam
def function1(func):
    def x():
        a=10
        return func(a)
    return x

@function1
def function2(y):
    return y


print(function2())
    

This should work…

Answered By: ItzKarizma
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.