所以我知道我不应该使用像这样的全局变量,但如果我要将var声明为全局变量,我将如何从另一个函数访问它。这似乎对我没用。请注意,我使用的是python 3.6
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)
答案 0 :(得分:1)
print (global 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
答案 1 :(得分:0)
您可以使用setattr:
x = XClass()
setattr( x, 'my_attr_name', 'value' )
print x.my_attr_name
答案 2 :(得分:0)
定义清理方法时出现语法错误。它应该工作,请检查;
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)