Python returns TypeError when method returns string
What's wrong with the code? Python returns a TypeError when the method returns a class string.
class window:
def __init__(self, title='window'):
self.title = title
def title(self, title):
if title:
self.title = title
else:
return self.title
window = window()
window.title('changed')
print(window.title())
Mistake:
Traceback (most recent call last):
File "C:/Users/Danilo/Desktop/pygtk.py", line 10, in <module>
window.title('changed')
TypeError: 'str' object is not callable
source to share
Methods are also attributes. You cannot reuse a name title
for a method and an attribute. In your instance, you are setting self.title
to a string, not a callable:
>>> class window:
... def __init__(self, title='window'):
... self.title = title
... def title(self, title):
... if title:
... self.title = title
... else:
... return self.title
...
>>> window().title
'window'
>>> window().title()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Python can no longer find a method in the class because the instance has an attribute with the same name.
Rename the attribute; use an underscore like:
class window:
def __init__(self, title='window'):
self._title = title
def title(self, title):
if title:
self._title = title
else:
return self._title
If you want the argument to title
be optional, you must use the keyword argument:
def title(self, title=None):
if title:
self._title = title
else:
return self._title
Now title
the default will be None
, and your test if title
will run correctly:
>>> window_instance = window()
>>> window_instance.title('changed')
>>> print(window_instance.title())
changed
Note that I also used a different name for the instance; you also don't want to mask the class.
source to share