problem with str()

7stud bbxx789_05ss at
Thu Mar 15 20:49:01 CET 2007

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()
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
['__doc__', '__init__', '__module__', 'num', 'num2', 'someFunc']
['__init__', 'someFunc']
I am init func!
<type 'str'>
Traceback (most recent call last):
  File "", 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.

More information about the Python-list mailing list