【问题标题】:Object oriented programming in Python: Mysterious Syntax Error - TV ObjectPython 中的面向对象编程:神秘的语法错误 - TV Object
【发布时间】:2017-07-11 02:12:11
【问题描述】:

因此,我需要编写一个程序,将电视模拟为 Python 教程书中的挑战对象(Python for the Absolute Beginner,第 8 章)。我认为大部分代码都类似于那一章中的 Critter Caretaker 程序。我还不知道一旦我解决了我将要提出的问题,这个程序是否会工作,因为我无法让它运行。

代码如下:

#TV Object

class TV(object):

    def __init__(self, volume = 50, channel = 1):
        self.volume = 50
        self.channel = 1
        print("You have turned on your TV")

    def change_channel(self, channel):
        print("This TV has three channels: News, Weather, and Soap Operas.")
        print("""
Which would you like to watch?
1 - News
2 - Weather
3 - Soap Operas    
    """)
        change = int(input(""))
        if change in range(1-3):
            channel = change
        return channel

    def set_volume(self, volume):
        print("The current volume is ", volume, ".")
        change = int(input("What volume level would you like (1-100)?:")
        if change in range(1-100):
                     volume = change
        return volume

    def watch(self, volume, channel):
         news = "Breaking News: U.S Senate to vote today on bill to use politicians for lab experiments."
         weather = "We're looking at a mostly sunny day with a slight chance of atomic anhiliation."
         soap = "John, I think I'm pregnant! And the father is your evil twin!"

         if channel == 1:
             program = news
         if channel == 2:
             program = weather
         if channel == 3:
             program = soap

         if volume == 70>:
            print(upper(program))
         elif volume == 30<:
              print(lower(program))
         else:
              print(program)

def main():
        tv = TV()

        choice = None
        while choice != "0":
            print \
            ("""
            0 - Turn it off
            1 - Change the channel
            2 - Set the volume
            3 - Watch TV
            """)

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

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

            #change the channel
            elif choice == "1":
                tv.change_channel(channel)

            #set volue
            elif choice == "2":
                tv.set_volume(volume)

            #watch TV
            elif choice == "3":
                tv.watch(volume, channel)

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



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

set_volume方法出现错误。

def set_volume(self, volume):
        print("The current volume is ", volume, ".")
        change = int(input("What volume level would you like (1-100)?:")
        if change in range(1-100):
                     volume = change
        return volume

一旦我到达“if change in range(1-100):”这行代码,pyshell 就会告诉我,我在冒号上做了一个语法错误。它没有给我更多关于那个错误是什么的信息。

另一个奇怪的现象是,在编写程序时,我从冒号移到下一行后的自动间距似乎关闭了;就像它将光标移动到太多空格上一样,好像它认为代码是针对前一个冒号之后的不可见子冒号的。起初我以为我可能没有完成前一行代码,但我似乎无法弄清楚它是什么。

是什么导致我的语法错误?

P.S:如果其他人注意到语法错误修复后会出现的其他代码问题,我将不胜感激。我是对象编程的新手,我可以使用我能获得的所有帮助。

【问题讨论】:

  • 您在这一行缺少右括号:change = int(input("What volume level would you like (1-100)?:")
  • 另外,range(1-100) 不会像你想象的那样做。
  • 如前文所述,您的range(1-100) 不正确。你想要range(1, 100)。但是,如果您实际打印 -> print(list(range(1, 100))),您会看到它实际上只转到 99。所以,你实际上想要range(1, 101)

标签: python object methods syntax-error


【解决方案1】:

你缺少右括号

# is
change = int(input("What volume level would you like (1-100)?:")
# Should be
change = int(input("What volume level would you like (1-100)?:"))

此外,您对 range 的调用应使用逗号分隔正在传递的第一个和第二个参数。

if change in range(1, 101):
    self.volume = change

还应该注意,逻辑仅在 python 2 中有效,因为range 的行为在 python 3 中发生了变化。在 2 中 range 返回一个列表,而在 3 中它是一个生成器。要在 python 2 中使用 range 的生成器版本,您必须改为调用 xrange

编辑

您需要将该方法的结果分配回通道/音量属性,而不是使用return。您可以通过 self 参数访问它们,该参数是对该对象的特定实例的引用。

【讨论】:

    【解决方案2】:
    def set_volume(self, volume):
        print("The current volume is ", volume, ".")
    
        # missing paren at the end of this line
        change = int(input("What volume level would you like (1-100)?:")
    
        # range(1-100) gives (1 through -100). 
        # You want either range(1+100) range(1,101).
        if change in range(1-100):
    
        # keep your indentation consistent
            volume = change
    
        return volume
    

    此外,您的类变量将不起作用。以下是我将如何编写函数:

    def set_volume(self):
        print("The current volume is ", self.volume, ".")
        new_volume = input("What volume level would you like (1-100)?:")
        if is_int(new_volume) and new_volume in range(1+100):
            self.volume = int(change)
    

    然后在主...

    elif choice == "2":
        tv.set_volume()
    

    这里发生的是TV 类是“类似于电视”的柏拉图式理想。所有电视都有音量和音量旋钮。但是你不能改变通用柏拉图式TV 的音量。

    因此,您创建了一个实例,即通用TV 的“物理”表现形式。您将此实例分配给变量tv

    现在,当您调用tv.set_volume() 时,这实际上调用了TV.set_volume(self=tv)self 参数是物理实例。使用 self 参数,函数可以控制音量和通道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多