Getting a TypeError when method returns string

偶尔善良 提交于 2019-12-07 13:11:29

问题


What's is wrong with the code? Python returns TypeError when method returns 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())

Error:

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

回答1:


Methods are attributes too. You cannot reuse the name title for both a method and an attribute. On your instance, you set self.title to a string, and that's not 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 the method on the class because the instance has an attribute with the same name.

Rename the attribute; use an underscore for example:

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 title argument to be optional, you should use a keyword argument:

def title(self, title=None):
    if title:
        self._title = title
    else:
        return self._title

Now title will default to None and your if title test will work 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 don't want to mask the class either.



来源:https://stackoverflow.com/questions/27549595/getting-a-typeerror-when-method-returns-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!