When I call func1 from func2, I get an error. Why is this occurring and how to access the returned dictionary d in func1 from func2?
func1()
NameError: name 'func1' is not defined
class ABC():
def func1(self, a):
d = {}
###do something with a
###return ending dictionary d
return d
def func2(self):
###Retrieve returned dictionary d from func1 and use
func1()
d['key'] = value
func1 and func2 are instance methods of ABC objects. You need to call them from the instance of such object.
In your case, one such instance is self, first parameter of both functions.
Thus, self.func1() will work.
Use self.func1() to call the function inside your class.
Related
i'm trying to get the value from an inside function func2, to put it outside without calling func1 and func2. Here is my program:
def func1():
def func2(x, y, z):
# global str
str = "Xin chao`"
# func2()
#func1()
print("Result:", str)
If you don't call the functions, that variable doesn't exists. You could declare it global but it will not take the value Xin chao if you don't call those functions
I want to use one of the attributes returned by a function in a python script (x) into a python script (y)
The communication between both scripts works well; I can get functions and attributes, but doesn't allow me to attributes returned by a function.
Here is how I worked:
x.py
def func():
b = 10
a = 15
return [a,b]
c = 20
y.py
from x import func
import x
print (x.c)
print (func.b)
I get the "c" value and the following error AttributeError: 'function' object has no attribute 'b'
I have tried also to print x.b, and I've got AttributeError: module 'WorkingLSTM' has no attribute 'b'
Thanks in advance
The way to call func is by using func(), which would give you [a,b].
example:
funcResult = func()
a = funcResult[0]
b = funcResult[1]
funcResults is the return value from func(), that is the list [a,b].
That's not allowed, you have to call the function to get the value from the functions returned list.
a, b = func()
print(b)
# or just...
print(func()[1])
PS: It's "not allowed" because it doesn't make sense in any way; when there is no function call, there is not variable b at all. You might take a look at classes, they can hold static variables.
you cannot access local variables of a function.
these variables exist only during the the time where func is executed and are destroyed afterwards.
You can of course call the function and look at the result, but the result is just a list with two values
rslt = func()
print("A = ", rslt[0])
print("B = ", rslt[1])
The variable was declared inside a function making it a local variable and as such it can"t be accessed outside the function.
The variable is declared outside of the function making it a global variable and is not in anyway tied to your function.
The concept of attributes relates to Classes and you are dealing with a function so you might have to treat it as a class object.
If you are concerned bout accessing the local variables, you might as well do this:
y.py
from x import *
d = func() # func returns a list which is now
# identified/referenced by variable d
# displays the elements in the list using index position
print(d[0])
print(d[1])
If you want to use attributes, you may create a callable class instead of function:
class Func:
def __init__(self):
self.b = 10
self.a = 15
def __call__():
return [self.a, self.b]
func = Func()
Python has the concept of the scope. Local variables have no effect outside the function.
If you want to use it, use class and self or make getter function(but it's not Pythonic).
x.py
class X:
def __init__(self):
self.b = 10
self.a = 15
self.c = 20
def func(self):
return [self.a, self.b]
y.py
from x import X
x = X()
print(x.c)
print(x.func()[1])
I have defined two functions(fun1 and fun2), which return some values and I call one of these functions in fun3. I can do if condition inside for loop but is there a way that the function can be chosen before. As shown here. Or is there any other approach?
def fun1(a1,b1)
def fun2(a1,b1)
def fun3(a1,b1,some_para):
if some_para:
sel_func = fun1()
else:
sel_func = fun2()
for Loop:
sel_func(a1,b1)
Functions are objects. Just assign the function instead of calling it. Using your example:
def fun3(a1, b1, some_para):
sel_func = fun1 if some_para else fun2
for Loop:
sel_func(a1, b1)
def fun1(a1,b1)
def fun2(a1,b1)
def fun3(a1,b1,some_para = None):
sel_func = fun1 if some_para else fun2
for Loop:
sel_func(a1,b1)
use some_para =None in function declaration, when you call this function you always need to pass the argument to it and only fun1 will run every time if you don't pass any value an attribute error will occur. if none uses and no value passed fun2 will execute else fun1 will.
You can pass the function as a parameter outside so it is easier to read:
def fun3(a1, b1, sel_func):
for Loop:
sel_func(a1, b1)
# call fun3 with whatever funtion you need in each momment
fun3(a, b, fun1)
fun3(a, b, fun2)
I have a function inside inside another and a third function. How can I call my nested function inside of my third function? Is there any special libraries I can use? I am not allowed to edit a() or b(), only c().
def a():
def b():
print("hi")
def c():
# code only here to call b() to print
When you do this, function b is defined locally within a. This means that it cannot be accessed by default outside of a. There are two main ways to solve this, but both involve modifying a:
The global keyword (not recommended)
def a():
global b
def b():
print("hi")
Here the global keyword sets b up as a global variable, so that you can then access it by calling it normally from within c. This is generally frowned upon.
Returning the function from a and passing it to c
def a():
def b():
print("hi")
return b
def c(b):
#your code
Then, when you call c, you should pass b to it, which a will have returned. You can either do so thus:
b = a()
c(b)
Or you can simply call a every time you call c, thus:
c(a())
If you choose to do this, you can then define c thus:
def c():
b = a()
#your code here
which would allow you to simply call c normally, thus:
`c()`
This is not possible due to the way that Python scope works. b() is local to a(), and so does not exist within c().
EDIT: commenter is correct, the suggestion I initially gave doesn't work -- so this definitely just isn't possible.
As explained here, you cannot directly call a function included inside another. But, you can play around a bit and make it indirectly possible.
You could try calling functions via arguments and parameter values to call the function you want inside another function.
def a(invoke=None):
def b():
print('b')
if invoke == 'b':
b()
def c():
a(invoke='b')
c()
The result is:
b
You can even pass arguments to these function if you want:
def a(invoke=None, a_parameter=None):
def b(b_parameter=None):
if b_parameter == None:
print('b')
if b_parameter == 'b1':
print('b1')
if b_parameter == 'b2':
print('b2')
if invoke == 'b':
b(b_parameter = a_parameter)
def c(parameter=None):
a(invoke='b', a_parameter = parameter)
c()
Result:
b
But:
c('b1')
Result:
b1
I am dealing with widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working example:
class Foo():
def parse(self, what):
self.bar = what
foo = lambda x = Foo(): (x.parse("All set"), x)[-1]
print(foo().bar)
'All set'
The lambda function needs to instantiate a class, call one of its members to parse a string and change its internal state, and return the instantiated class. The only way to do this that I can think of at the moment is as shown in the above example: pass the instance as the default argument, create a list where the first element is the call to the method and the second is the instance itself, then select the last element.
Is there a more pythonic and elegant way of obtaining the same result?
EDIT: A few caveats: In the actual code the class Foo is defined in other modules, and I'm passing the lambda as an argument to another function, hence why I don't really need to name the callback. Indeed, what I actually have is something that looks like
widget.bind( 'some_signal', lambda t, x = Foo(): (x.parse(t), x)[-1] )
The most pythonic solution is to not use a lambda:
def foo():
x = Foo()
x.parse("All set")
return x
print(foo().bar)
Lambdas in python are a syntactic convenience and are strictly less powerful than named functions.
A factory function achieves the goal of avoiding a separate named function in the code that wires the callback. I would consider this pythonic. Using a lambda function that does what you have to do ist definitely not pythonic.
def create_callback(data):
def callback():
x = Foo()
x.parse(data)
return x
return callback
What about
def callback():
x = Foo()
x.parse("All set")
return x
widget.bind('some_signal', callback)
Note that your lambda will instanciate Foo() only the first time the code is interpreted.
Indeed,
foo = lambda d=dict(): d
d = foo()
d['hello'] = 'world'
print(foo()) # This will print {'hello': 'world'} instead of {}
based on #Vaibhav Sagar answer, a bit modified:
class Foo():
def parse(self, what):
self.bar = what
def foo_factory(what):
instance = Foo()
instance.parse(what)
return instance
all_set = foo_factory('All set')
ok = foo_factory('Ok')
ready = foo_factory('ready')
print(all_set)
print(all_set.bar)
print(ok)
print(ok.bar)
print(ready)
print(ready.bar)
Output:
<__main__.Foo object at 0x7f56a176cc50>
All set
<__main__.Foo object at 0x7f56a176cc88>
Ok
<__main__.Foo object at 0x7f56a176ccf8>
ready