Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables in Python 3 class

How to use a global variable inside the initialiser of a class in Python 3?

for eg

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

How do I convert x into a global variable?

like image 351
sgp Avatar asked Aug 11 '26 03:08

sgp


1 Answers

You have to declare your variable before the class declaration and use the global statement on the init function:

import urllib
from urllib.request import urlopen

x = None

class ABC(object):

 def __init__(self):
   global x
   x=urlopen('http://www.google.com/').read()
like image 138
Renato Todorov Avatar answered Aug 13 '26 19:08

Renato Todorov