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)()
Related
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 5 years ago.
Improve this question
I stumbled upon an interesting and unexpected feature of Python:
def fun():
"""Foo’s docstring"""
is a valid function? According to PEP 257, “A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition” meaning that the docstring itself is considered a statement?
I would have expected that at least a pass statement is required here. The above example contradicts the Python Zen of “explicit is better than implicit” as pass states an explicit intent, and a docstring does not.
Can anybody shed some light on the intent?
A string literal is just like any other literal. It also works if you just put in an integer:
def func():
1
However, it doesn't work if you only use a comment:
def func():
# test
# IndentationError: expected an indented block
Even though it's also added as docstring (saved in the __doc__ attribute) it's also a function level constant:
def func():
"""I'm a function"""
>>> func.__code__.co_consts
("I'm a function", None)
So the presence of a string literal as only content of a function doesn't change how the function is actually "parsed" and "compiled" itself. Well, apart from the fact that it also got a not-None __doc__ attribute.
It's actually very handy for abstractmethods (see for example "Body of abstract method in Python"), where you don't need an actual function body.
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})
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I currently have a class that turns my list of lists into a list of objects, where every object has a certain amount of stuff from the constructor. Lets say they have names, and some random numbers.
What I would like to do is print all of these objects simultaneously, where each object is one line. How would I go about doing this, I tried making a Str function, but it still returns ""
Okay, I have a class which has 10 objects, these have the attributes self.planet, self.distance, self.distsquared, self.radius, self.diamater where distance/distsquared/radius/diamater are all integers and I have a function which is supposed to print all of the planets after their distance, with the furthest distance highest. But when I try to make a function return "" % (self.planet, self.distance, self.distsquared, self.radius self.diameter) it still only prints I want every object to be printed
Thanks in advance!
For a list of objects, you can print them neatly using:
print("\n".join(str(x) for x in object_list))
The class should have the function to make each object into a string as follows:
def __str__(self):
return "Attr1: {0.attr1}, Attr2: {0.attr2}, ...".format(self)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This seems like such a simple question, but there don't seem to be any answers that address my particular issue, which is why the init method never actually initiates the class instance variable 'listlist'.
class PointsList():
def _init_(self):
self.listlist = [None]
def addtolist(self,item):
self.listlist.append(item)
def getlist(self):
return self.listlist
a = PointsList()
a.addtolist('Scarlet')
print a.getlist()
Running the above code gives me:
AttributeError: PointsList instance has no attribute 'listlist'
The error is traced to line 5 when the 'addtolist' method attempts to add an item to the evidently nonexistent 'listlist' instance variable.
I've checked the indentation many times but it appears to be sound. Is there something wrong with my Python installation? I am using Python v2.7.5 (haven't gotten around to 2.7.6 yet) and the Spyder IDE v2.2.0
Python special methods use two underscores at the start and end; you need to name the initializer __init__, not _init_:
class PointsList():
def __init__(self):
self.listlist = [None]
Underscore characters are usually shown connecting up forming a longer line, but there are two underscores before init, and two after.
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.