Python: Call an object from 'n string value [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I sincerely hope this is not a duplicate, but I cannot find an answer (you'll notice that I don't even know how to ask the question!).
I have python code with one class and many def. It would take too much time to explain why I would want to do the following, but I sure would be able to:
class A:
def a(self):
some argument
def b(self):
another argument
So to call the def's, I just put:
A().a()
A().b()
What I would like to do is have a third def that looks like this:
def c(self):
process = [A().a(), A().b(), A().a(), A().a()] #This sequence is just an example - there are many more def's.
for i in process:
print 'Hello'
i
print 'Bye'
I don't know if this makes any sense? What happens currently is the process part is called and the two print lines are printed several times thereafter.
Thanks.

Might this work?
def c(self):
process = [self.a, self.b, self.a, self.a]
for i in process:
print 'Hello'
i()
print 'Bye'
In your original example, instead of storing the functions, you were calling them already when the list was built. The return values from your methods got stored in the list, so that is why they could not be called later.

Related

Is indirect recursion possible in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I tried searching online but did not find any answer to this particular question. In python there are no function declarations and a function can't be used until it has been defined.
Does this mean that indirect recursion is impossible in python?
And is there a way around this by using some modules?
No, it is possible
def f():
print('from f')
g()
def g():
print('from g')
f()
"a function can't be used until it has been defined" is not so straightforward. When the code runs, the name of the objects that it refers to have to exist. So, you can't do
f()
def f():...
because f() actually executes something. But definitions create a function object, without running it at the time. In the example, the function is claled at the last line of the script, and, by that time, both f, g do exist.

How do I stub functions in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
It's my first few lessons in programming and i've encountered a question that i don't really understand how to proceed.
def defeat_balrog(protagonist):
def spawn_balrog():
"""Spawns and returns a stubborn balrog"""
pass
def balrog_attack(balrog, person):
"""Returns an attack move from the balrog's repertoire"""
pass
cave_balrog = spawn_balrog()
is_balrog_defeated = False
yell(protagonist, 'You cannot pass!')
while not is_balrog_defeated:
current_attack = balrog_attack(cave_balrog, protagonist)
if current_attack != None:
take_defensive_action(protagonist, current_attack)
yell(protagonist, 'YOU SHALL NOT PASS!')
take_offensive_action(protagonist, cave_balrog)
is_balrog_defeated = True
return True
def take_defensive_action(attacked_entity, attack_move):
"""
attacked_entity anticipates attack_move and defends himself.
"""
pass
#my stubs here#
defeat_balrog('gandalf')
I'm supposed to identify the remaining functions that have been wishfully used, but for which stubs have not been created, and fill in from the last line #my stubs here#. not sure how to get started or proceed on.
A stub is a function that exists but for which no meaningful business logic has been defined. For example:
def take_defensive_action(attacked_entity, attack_move):
pass
Notice the pass statement here? It means that you've defined a valid function, but it does nothing.
Pasting your code into PyCharm, I see the following functions highlighted in "yellow" (that means those function names have an Unresolved reference):
yell(protagonist, 'YOU SHALL NOT PASS!')
take_offensive_action(protagonist, cave_balrog)
Clear on the meaning of what a stub is, you should be able to define these functions accordingly as they haven't been defined yet. Here's an example for yell:
def yell(protagonist, message):
pass
I leave the second to you.

How to pass function as argument without executing it? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have this function:
def a(one, two, the_argument_function):
if one in two:
return the_argument_function
my the_argument_function looks something like this:
def b(do_this, do_that):
print "hi."
Both of the above are imported to a file "main_functions.py" for my ultimate code to look like this:
print function_from_main(package1.a, argument, package2.b(do_this, do_that)
The "if one in two" from "a"function works but "b"function still executes when being passed to "function_from_main" without waiting the check from "a" to see if it actually should execute.
What can I do?
package2.b(do_this, do_that) is a function call (a function name followed by parenthesis). Instead you should be passing only the function name package2.b the function a
You will also need to modify function a such that function be is called when the condition is satisfied
# function a definition
def a(one, two, the_argument_function, argument_dict):
if one in two:
return the_argument_function(**argument_dict)
def b(do_this, do_that):
print "hi."
# function call for a
a(one, two, b, {'do_this': some_value, 'do_that': some_other_value})

Is it a good habit to print the bool value from a function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
def f():
return True
print(f())
or
def f():
return True
if f():
print('True')
else:
print('False')
Should I round it in if statement or simply print out the value, in Python 3.3.2?
print automatically converts input to its string representation. So, the two methods actually do the exact same thing. Considering that, why not use the first? It is a lot cleaner.
Also, the second method can really be simplified:
print('True' if f() else 'False')
Having that much code for something so simple isn't necessary.
If your function always returns a bool, then just print it, like this:
print(f())
If you need to convert it to a string without printing it, use str(f()) or repr(f()). For the bool type these two are equivalent, but e.g. if their argument is an str, they are different: repr(str_obj) returns it properly quoted and escaped.
If it's not always a bool, but you want to print something depending on its truth value, then use an if, like in your question or in iCodez' answer. Alternatively, you can convert it to a bool, and then print it:
print(bool(f()))
Personally, the:
print(f())
form looks nicer. However, one thing to consider is that you have baked in a call to print what is essentially debugging output with the call that is causing the functionality to be invoked. This would make it painful later when you want to turn off all the annoying print statements when you are ready to build upon your program.
You could instead have a function such as:
LOGGING_ENABLED = True
def print_if(my_bool):
if LOGGING_ENABLED:
print str(my_bool)
This will ensure that the function is always invoked but the debug output happens only if you want it.

Execute all functions from module [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
class MyClass(object):
def fn():
return 1
for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]:
print i(MyClass) // Error here
Error: TypeError: 'str' object is not callable
If i change print statement to:
print "%s(MyClass)" % i
this simply print:
ArgInfo(MyClass)
and so on...
dir(module) returns a list of names (strings) defined in the module, not the actual functions or values. To get those, use getattr, which you already use for the callable check.
for name in dir(your_module):
might_be_function = getattr(your_module, name)
if callable(might_be_function):
print might_be_function(your_parameters)
Of course, it might still be the case that the function is not applicable to the given parameters, so you might want to check this first, or wrap in in a try block.
Do you need to call all methods by name like that?
class C1:
def f1(self):
print('f1---')
def f2(self):
print('f2---')
inspect = C1()
for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]:
getattr(inspect, i)()

Categories