On Mar 15, 2:49 pm, "7stud" <[EMAIL PROTECTED]> wrote: > I can't get the str() method to work in the following code(the last > line produces an error): > > ============ > class test: > """class test""" > def __init__(self): > """I am init func!""" > self.num = 10 > self.num2 = 20 > def someFunc(self): > """I am someFunc in test!""" > print "hello" > > obj = test() > obj.someFunc() > names = dir(obj) > print names > > methodList = [str for str in names if callable(getattr(obj, str))] > print methodList > > x = getattr(obj, methodList[0]).__doc__ > print x > print type(x) > print str(getattr(obj, methodList[0]).__doc__) > =========== > > Here is the output: > > $ python test1.py > hello > ['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc'] > ['__init__', 'someFunc'] > I am init func! > <type 'str'> > Traceback (most recent call last): > File "test1.py", line 23, in ? > print str(getattr(obj, methodList[0]).__doc__) > TypeError: 'str' object is not callable > > This is part of some code in Diving Into Python,Chapter 4. In case a > function doesn't have a __doc__ string, and therefore __doc__ returns > None, the code needs to convert each __doc__ to a string so that the > result is guaranteed to be a string.
Your string comprehension over wrote the str built-in method, turning it into a variable. If you just type "str" (without the quotes) into the interpreter, it'll spit out 'someFunc'. Thus, you cannot use str as the iterator in your code: methodList = [str for str in names if callable(getattr(obj, str))] instead, do something like this: methodList = [i for i in names if callable(getattr(obj, i))] Have fun! Mike -- http://mail.python.org/mailman/listinfo/python-list