Class Python 3类中的全局变量

Class Python 3类中的全局变量,class,python-3.x,initialization,global-variables,Class,Python 3.x,Initialization,Global Variables,在Python3中,如何在类的初始化器中使用全局变量 例如 import urllib from urllib.request import urlopen class ABC(object): def __init__(self): x=urlopen('http://www.google.com/').read() 如何将x转换为全局变量?必须在类声明之前声明变量,并在init函数上使用global语句: import urllib from urllib.request impo

在Python3中,如何在类的初始化器中使用全局变量

例如

import urllib
from urllib.request import urlopen
class ABC(object):
 def __init__(self):
   x=urlopen('http://www.google.com/').read()

如何将x转换为全局变量?

必须在类声明之前声明变量,并在init函数上使用global语句:

import urllib
from urllib.request import urlopen

x = None

class ABC(object):

 def __init__(self):
   global x
   x=urlopen('http://www.google.com/').read()

如果我打印x,则表示无。但是我希望它返回源代码。很抱歉,您必须在init函数中声明global,而不是在类声明中!我编辑了答案,现在可以了!