sgp
sgp

Reputation: 1778

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?

Upvotes: 3

Views: 10441

Answers (1)

Renato Todorov
Renato Todorov

Reputation: 560

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()

Upvotes: 8

Related Questions