简体   繁体   English

全局变量在 function 之外不起作用

[英]Global variable doesn't work outside the function

I need your help.我需要你的帮助。 Why I get this error?为什么我会收到此错误? title is assigned as global variable, so I should get 'None' printed out, right?标题被分配为全局变量,所以我应该打印出“无”,对吗?

def get_history_events(requests, BeautifulSoup):
    global title, facts
    title = facts = None

    url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}

    r = requests.get(url, headers=header).text
    soup = BeautifulSoup(r, 'lxml')

    table = soup.find('div', class_ = 'mainpage-block calendar-container')
    title = table.find('div', class_ = 'mainpage-headline').text
    facts = table.find('ul').text

print(title)
# NameError: name 'title' is not defined

You need to either declare the variable in global scope first您需要先在全局 scope 中声明变量

eg:例如:

title = None
def get_history_events(requests, BeautifulSoup):
    global title, facts
    title = facts = None

    url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}

    r = requests.get(url, headers=header).text
    soup = BeautifulSoup(r, 'lxml')

    table = soup.find('div', class_ = 'mainpage-block calendar-container')
    title = table.find('div', class_ = 'mainpage-headline').text
    facts = table.find('ul').text

print(title)

or execute your funtion before calling print on it: eg.:或在调用 print 之前执行您的功能:例如:

def get_history_events(requests, BeautifulSoup):
    global title, facts
    title = facts = None

    url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}

    r = requests.get(url, headers=header).text
    soup = BeautifulSoup(r, 'lxml')

    table = soup.find('div', class_ = 'mainpage-block calendar-container')
    title = table.find('div', class_ = 'mainpage-headline').text
    facts = table.find('ul').text

get_history_events(<imagine your args here>)
print(title)

You haven't run your function yet - so your global statement has never been seen by running code.你还没有运行你的 function - 所以你的全局语句从未被运行代码看到。

To make your code work, call your function first:要使您的代码正常工作,请先调用您的 function:

get_history_events(...)
print(title)

Here is an excellent set of examples for global use: https://www.programiz.com/python-programming/global-keyword这是一组供全球使用的优秀示例: https://www.programiz.com/python-programming/global-keyword

Thanks to everyone.谢谢大家。 Fixed.固定的。 Working properly.好好工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM