Python 3类中的全局变量

sgp*_*sgp 1 initialization class global-variables python-3.x

如何在Python 3中使用类的初始化内部的全局变量?

例如

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

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

Ren*_*rov 7

您必须在类声明之前声明您的变量,并在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()
Run Code Online (Sandbox Code Playgroud)