Python 方法返回字符串时获取TypeError
代码有什么问题?当方法返回类字符串时,Python返回TypeErrorPython 方法返回字符串时获取TypeError,python,string,class,methods,return,Python,String,Class,Methods,Return,代码有什么问题?当方法返回类字符串时,Python返回TypeError class window: def __init__(self, title='window'): self.title = title def title(self, title): if title: self.title = title else: return self.title window = w
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())
错误:
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
回溯(最近一次呼叫最后一次):
文件“C:/Users/Danilo/Desktop/pygtk.py”,第10行,在
window.title('changed')
TypeError:“str”对象不可调用
方法也是属性。不能对方法和属性重复使用名称title
。在您的实例中,您将self.title
设置为一个字符串,该字符串不可调用:
>>> 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
如果希望title
参数是可选的,则应使用关键字参数:
def title(self, title=None):
if title:
self._title = title
else:
return self._title
现在title
将默认为None
,您的if title
测试将正常工作:
>>> window_instance = window()
>>> window_instance.title('changed')
>>> print(window_instance.title())
changed
注意,我还为实例使用了不同的名称;您也不想屏蔽该类。我怀疑这与您使用
title
作为变量和函数的名称有关
>>> window_instance = window()
>>> window_instance.title('changed')
>>> print(window_instance.title())
changed