【问题标题】:Make a Tv simulator - Python制作电视模拟器 - Python
【发布时间】:2016-10-05 14:15:00
【问题描述】:

我对 Python 很陌生,我必须制作一个电视模拟器。我基本上搜索了整个网络,但我真的找不到我的答案。我的问题是我们必须将电视的状态保存在一个文件中,当我们重新打开程序时,它必须检索其先前的状态,即频道、节目、音量。我使用 pickle 保存文件,但它不会检索以前的状态。

希望我已经足够具体,否则请随时要求我澄清。

提前谢谢你

class Television(object):
    currentState = []

    def __init__(self,volume,channel,show):
        self.volume=volume
        self.channel=channel
        self.show=show

    def changeChannel(self,choice):

        self.channel=choice 
        return self.channel

    def increaseVolume(self,volume):
        if volume in range(0,9):
            self.volume+=1
        return self.volume

    def decreaseVolume(self,volume):
        if volume in range(1,10):            
            self.volume-=1        
        return self.volume

    #def __str__(self):
        #return "[channel: %s show: %s,volume: %s]" % (self.channel, self.show, self.volume)
    def __str__(self):
        return  "Channel: "+str(self.channel)+\
                "\nShow: "+ str(self.show)+\
                "\nVolume: "+ str(self.volume)
                                #printing object, state = "print(object)"
    def getState(self):         
        return self.volume

    def setState (self,channel,show):
        self.volume=5
        self.channel=channel[1]
        self.show=show[1]


#####################################################################

from tvsimulator import* 

import pickle, os.path

#from builtins import int

channel = ["1. Mtv","2. Tv 3","2. Svt","4. Kanal4"]

show = ["Music is life", "Har du tur i karlek?", "Pengar ar inte allt","Vem vill inte bli miljonar"]

volume = 5

global myTv

livingRoomTv = Television(channel,show,volume)

kitchenTv = Television(channel,show,volume)  




def saveFile(): 

    with open("tvState.pkl",'wb') as outfile:

        pickle.dump(livingRoomTv,outfile)
        pickle.dump(kitchenTv,outfile)

def importFile():       

    with open("tvState.pkl",'rb') as infile:

        livingRoomTv = pickle.load(infile)
        kitchenTv = pickle.load(infile)


def channelMenu(myTv):    
    for i in channel:
        print(i)                
    choice =int(input(print("Which channel do you want?")))
    choice = channel[choice-1]                    
    myTv.changeChannel(choice)
    selection =myTv.changeChannel(choice) 
    return selection   


def methodSelection(myTv):  

    print("1: Change channel")
    print("2: Volume Up")
    print("3: Volume Down")
    print("4: Return to main menu")       
    choice = int(input(print("\nPleas make a selection from the above list\n")))   
    print(myTv)
    try:                    
        if choice ==1:   
            channelMenu(myTv)
            print(myTv)          
            methodSelection(myTv)
        if choice ==2:
            myTv.increaseVolume(volume)
            print(myTv)
            methodSelection(myTv)
        if choice ==3:
            myTv.decreaseVolume(volume)
            print(myTv)
            methodSelection(myTv)
        if choice ==4:
            mainMenu()
    except:
        print("Wrong selection, please try again")




def mainMenu(): 

    print("1: Livingroom Tv")
    print("2: Kitchen TV")
    print("3: Exit\n")    
    choice = int(input(print("Please make a selection from the above list")))          
    try:              
        if choice == 1:
            print("Living room\n")       
            print(livingRoomTv)
            myTv = livingRoomTv        
            methodSelection(myTv)       
        if choice == 2:
            print("Kitchen\n")      
            print(kitchenTv)
            myTv=kitchenTv        
            methodSelection(myTv)        
        if choice == 3:
            saveFile()
            print("Tv Shut Down")
            exit
    except:
        print("Wrong selection, please try again")



def startUp():

    if os.path.isfile("tvState.pkl"):
        print("Tv restored to previous state")
        importFile()
        kitchenTv.getState()
        livingRoomTv.getState()
        mainMenu()               

    else:
        print("Welcome")
        kitchenTv.setState(channel, show)
        livingRoomTv.setState(channel, show)
        saveFile()
        mainMenu()    

startUp()  

【问题讨论】:

  • 解决任何问题的方法是减少它,直到只剩下问题的核心。在这种情况下;从你的程序中删除一些东西,直到你只剩下你无法工作的东西。也许这将是一个从文件中读取状态并打印出来的程序?然后你解决这个问题,并把所有其他的东西放回去。
  • 请发minimal reproducible example。我认为您不需要那堵代码墙来显示您对泡菜的问题。
  • "我基本上搜遍了整个网络" 你肯定已经这样做了一段时间了。
  • @MagnusHoff 谢谢你的建议。下次我会试试的。
  • @Goyo 现在问题已经解决,但我会保留它以备将来参考。只是我是编码新手,所以我不知道究竟是什么会影响程序。

标签: python pickle


【解决方案1】:

使用全局变量进行读取是没有问题的,因此说明save 功能有效,但分配给全局变量不是自动的:您必须将变量设为全局变量,否则它将创建局部变量,而这些变量很快就会丢失因为它们超出了范围(从而解释了为什么您的状态没有重新加载)。

可以通过添加global v 来访问全局变量,其中v 是在函数中被视为全局变量:

def importFile():       
    global livingRoomTv # link to the global variable
    global kitchenTv    # link to the global variable

    with open("tvState.pkl",'rb') as infile:

        livingRoomTv = pickle.load(infile)
        kitchenTv = pickle.load(infile)

简单的 MCVE:

z=[1,2,3]

def load():
    #global z
    z=set()

load()

print(z)

打印[1,2,3]

现在取消注释global z,它打印set([]),这意味着我成功地能够在函数中更改z

【讨论】:

  • 非常感谢您的快速回答。你解决了我的问题。我真的很感谢你浏览了整个代码“墙”,我知道它很乱,所以下次我有问题时,我会尽量减少代码。
  • 我没有穿过“墙”。我刚刚检查了加载/保存例程并了解它与全局变量有关(这是一个真正的陷阱,所以我经常使用单例类,因此我只能操作成员变量,而不是全局变量)。注意我的minimal reproducible example,它有 5 行长。
猜你喜欢
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多