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()
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()
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.
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
def function1(func):
def x():
a=10
return func(a)
return x
@function1
def function2(y):
return y
print(function2())
This should work…
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()
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()
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.
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
def function1(func):
def x():
a=10
return func(a)
return x
@function1
def function2(y):
return y
print(function2())
This should work…