学习Python 3.3 - TypeError:'int'对象不可调用

时间:2014-01-03 03:59:18

标签: oop python-3.3

我试图在“绝对初学者的Python编程”课程章节(第8章)结尾处解决挑战2,该声明如下:

  

通过将电视创建为对象来编写模拟电视的程序。用户应该能够输入频道号码并提高或降低音量。确保频道编号和音量级别保持在有效范围内。

我一直得到:TypeError:'int'对象不可调用,在这个阶段对它不是很有帮助。 我是一个初学者,但我已经看到了一些非常相似的工作(请参见我的代码下方的右下角)并且差不多复制了那些代码。有人可能会解释这有什么问题,以及如何让它发挥作用?

这是完整的错误:

Traceback (most recent call last):
  File "Untitled 3.py", line 59, in <module>
    main()
  File "Untitled 3.py", line 50, in main
    tv.channel(newchannel = int(input("What channel would you like to set the TV to?")))
TypeError: 'int' object is not callable

我的代码如下,

由于

class Television(object):
    """a TV"""
    def __init__(self, channel = 0, volume = 0):
        self.channel = channel
        self.volume = volume

    def channel(self, newchannel = 0):
        if newchannel <= 0 or newchannel >9:
            print("No negative numbers or numbers higher than 9. Start again from the menu")
        else:
            self.channel = newchannel
            print("You set the TV on channel", self.channel)

    def volume(self, newvolume = 0):
        if newvolume <= 0 or newvolume >9:
            print("No negative numbers or numbers higher than 9. Start again from the menu")
        else:
            self.volume = newvolume
            print("You set the TV on volume", self.volume)

    def watch(self):
        print("You are watching channel", self.channel, "at volume", self.volume)

def main():
    tv = Television()

choice = None  
while choice != "0":
    print \
    ("""
    TV

    0 - Quit
    1 - Watch the TV
    2 - Change channel
    3 - Set the volume
    """)

    choice = input("Choice: ")
    print()

    # exit
    if choice == "0":
        print("Good-bye.")

    elif choice == "1":
        tv.watching()

    elif choice == "2":
        tv.channel(newchannel = int(input("What channel would you like to set the TV to?")))

    elif choice == "3":
        tv.volume(newvolume = int(input("What channel would you like to set the TV to?")))

    # some unknown choice
    else:
        print("\nSorry, but", choice, "isn't a valid choice.")

main()
("\n\nPress the enter key to exit.")

为什么以下工作呢?对我而言,它看起来与我所做的非常相似。

class Critter(object):
    """A virtual pet"""
    def __init__(self, hunger = 0, boredom = 0):
        self.hunger = hunger
        self.boredom = boredom

    def eat(self, food = 4):
        print("Brruppp.  Thank you.")
        self.hunger += food
        if self.hunger < 0:
            self.hunger = 0


crit = Critter()
print(crit.hunger)
crit.eat(food = int(input("how much do you want to feed him?")))
print(crit.hunger)

1 个答案:

答案 0 :(得分:1)

问题是您要定义一个与属性同名的方法。也就是说,你说Television.channel是一个int,但后来你将一个方法绑定到该名称。