Getting a TypeError when method returns string

♀尐吖头ヾ 提交于 2019-12-06 02:25:38

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.

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