python中的全局变量工作不正常?
所以我知道我不应该像这样使用全局变量,但如果我将一个变量声明为全局变量,我将如何从另一个函数访问它。这似乎对我不起作用。请注意,我使用的是python 3.6python中的全局变量工作不正常?,python,Python,所以我知道我不应该像这样使用全局变量,但如果我将一个变量声明为全局变量,我将如何从另一个函数访问它。这似乎对我不起作用。请注意,我使用的是python 3.6 from bs4 import BeautifulSoup import requests import urllib.request def f1(): url = "some url" source_code = requests.get(url
from bs4 import BeautifulSoup
import requests
import urllib.request
def f1():
url = "some url"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for td in soup.find_all('td'):
global tlist
tlist = list(td)
print(tlist)
def cleaned():
global tlist
print(global tlist)
打印(全局tlist)
是一个语法错误;通过将global
语句放在单独的一行中,可以使其工作
>>> def f1():
... global x
... x = 1
...
>>> def f2():
... print(global x)
File "<stdin>", line 2
print(global x)
^
SyntaxError: invalid syntax
>>> def f2():
... global x
... print(x)
...
>>> f1()
>>> f2()
1
>>def f1():
... 全球x
... x=1
...
>>>def f2():
... 打印(全局x)
文件“”,第2行
打印(全局x)
^
SyntaxError:无效语法
>>>def f2():
... 全球x
... 打印(x)
...
>>>f1()
>>>f2()
1.
您可以使用setattr:
x = XClass()
setattr( x, 'my_attr_name', 'value' )
print x.my_attr_name
定义清除方法时出现语法错误。它应该可以工作,请检查
from bs4 import BeautifulSoup
import requests
import urllib.request
def f1():
url = "some url"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for td in soup.find_all('td'):
global tlist
tlist = list(td)
print(tlist)
def cleaned():
global tlist
print(tlist)
我认为您还需要在主代码中定义tlist。然后使用global在函数中全局访问它
print(global tlist)
是一个语法错误global
是一个语句。要扩展Daniel所说的内容,函数参数需要是表达式,Python中的语句不是表达式。顺便说一句,请不要将global
语句深埋在函数体中,请将它们放在函数体的顶部,它们在逻辑上属于的位置。global
语句通过整个函数影响全局名称的查找,而不仅仅是在global
语句本身之后出现的语句中。但是隐藏在函数中的global
语句意味着它只影响它下面的代码,因此这是误导性的。谢谢。这正是我需要的。谢谢你的帮助。