在Python中使用另一个函数中的一个变量

2024-04-27 13:59:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,下载视频文件在这里它是完整的,别担心它是一个短程序。在

import pafy

def download():
    url = raw_input('Please enter the path to the video\n')
    video = pafy.new(url)
    vid_title = video.title
    best = video.getbest()
    streams = video.streams
    print(vid_title)
    for stream in streams:
        print(stream)
    print'Resolution: ',best.resolution,'\nExtension : ', best.extension
    user_choice = raw_input("Do you want to download this video\ny or n\n")
    if user_choice == 'y':
        print'Your video will downloaded soon'
        filename = best.download(filepath = '/home/mark/new_projects')
        another_download()
    elif user_choice =='n':
        print'You have chosen not to download a video'
        another_download()


def another_download():
    another_choice = raw_input('Would you like to download another video\ny or n\n')
    if another_choice == 'y':
        download()
    else:
        print'Thank for using my program'

download()

我想把它分解成更小的函数。我试过这样做:

^{pr2}$

但当我尝试这个时,我得到一个错误,告诉我最好的还没有被宣布。我不想将best声明为全局变量。有没有办法在另一个函数中使用一个函数中的变量?在


Tags: to函数程序inputrawtitledownloadvideo
2条回答

这里有几个选择。我会尽力把它们布置好。在

选项1:假设您首先调用download(),那么您可以让url()返回所需内容并将其存储在download()方法中的变量中:

def url():
    url = raw_input('Please enter the path to the video\n')
    video = pafy.new(url)
    vid_title = video.title
    best = video.getbest()
    streams = video.streams
    print(vid_title)
    for stream in streams:
        print(stream)
    print'Resolution: ',best.resolution,'\nExtension : ', best.extension
    return best

def download():
    user_choice = raw_input("Do you want to download this video\ny or n\n")
    if user_choice == 'y':
        best = url()
        print'Your video will downloaded soon'
        filename = best.download(filepath = '/home/mark/new_projects')
        another_download()
    elif user_choice =='n':
        print'You have chosen not to download a video'
        another_download()

选项2:您可以使用全局变量,但我不知道在这种情况下使用它们的后果:

^{pr2}$

我认为这两种解决方案中的任何一种都能满足您的需要,但在这种特殊情况下,我推荐第一种解决方案,因为它看起来不像是一个复杂的程序。在

将一个大函数拆分成更小的函数是一个好习惯,但更紧迫的问题是,您应该使用主循环并使函数返回,而不是像那样链接它们。在

现在download()->;另一个\u download()->;download()->;另一个\u download()->;…,因此,如果用户想下载n个视频,您将有n*2-1个函数挂起,直到最后一个完成。在

顺便回来解决你的问题:

def url():
    ...
    return best 

def download():
    best = url()
    ...

相关问题 更多 >