ITPub博客

首页 > 应用开发 > IT综合 > TypeError: 'str' object is not callable

TypeError: 'str' object is not callable

原创 IT综合 作者:a635186971 时间:2018-04-11 23:59:34 0 删除 编辑
如下代码:

点击(此处)折叠或打开

  1. class Person(object):
  2.     def __init__(self,name,age,race,nation,sex):
  3.         self.name = name
  4.         self.age = age
  5.         self.race = race
  6.         self.nation = nation
  7.         self.sex = sex
  8.         self.money = 0
  9.         self.workName = None
  10.         print "%s 的年龄是 %s ,是%s ,是%s 人,%s 的。" % (self.name,self.age,self.race,self.nation,self.sex)
  11.     
  12.     def love(self,name):
  13.         choice = raw_input("%s 是否爱 %s ?" % (self.name,name))
  14.         if choice == 'Y' or choice == 'y':
  15.             self.love = name
  16.             print "%s 爱上 %s " % (self.name,self.love)
  17.         else:
  18.             self.love = None
  19.             print "%s 不爱 %s " % (self.name,self.love)
  20.             
  21.             
  22. peter = Person("peter",26,'黄种',"中国","男")
  23. peter.love("liz")
  24. peter.love("liz")

错误信息:

点击(此处)折叠或打开

  1. peter 的年龄是 26 ,是黄种 ,是中国 人,男 的。
  2. peter 是否爱 liz ?y
  3. peter 爱上 liz
  4. Traceback (most recent call last):
  5. File "F:\python_src\Day4_hw\test.py", line 46, in
  6. peter.love("liz")
  7. TypeError: 'str' object is not callable
比较神奇的在于第一次调用peter实例的love方法不会报错,第二次调用才报错。
排查了不少时间,才发现是person类有问题,拥有love属性和love方法。
在python中,一个类不能有同名的属性和方法。
至于为什么不行,目前还不知道。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31441616/viewspace-2152827/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: day1-4
请登录后发表评论 登录
全部评论

注册时间:2017-03-07

  • 博文量
    41
  • 访问量
    57845