[Tutor] class.__repr__: 'str' object is not callable???
pan@uchicago.edu
pan@uchicago.edu
Thu May 1 21:26:01 2003
Thx to Anton, Don and Danny for soving my puzzle. Now I learned
a little bit more about py class.
Ok for Danny's 2 review questions:
###
>>> class BuggyClass:
.. def __init__(self):
.. self.name = 'pan'
.. def name(self):
.. return "My name is " + self.name
..
> >>> b = BuggyClass()
> >>>
> >>> b.name() ## Review Question: why doesn't this work? [A]
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: 'str' object is not callable
> >>>
> >>>
> >>>
> >>> BuggyClass.name(b) ## Advanced question: why does this work? [B]
> 'My name is pan'
> ###
My current understanding is:
in [B] the class hasn't been 'initialized' yet, so there's
no '.name' attribute. The only thing in the namespace with
name = 'name' is the function .name() which returns
'My name is pan'.
In [A] the class has been instanciated into 'b', meaning that
the attribute 'name' exists and having a string value 'pan',
which is returned when b.name is called. It's equivalent to
'pan'() so it results in a
'str' object is not callable
error.
Question: where is the .name() method after the class
is instanciated ? Simply overridden by the .name attribute
and can no longer be accessed ?
pan