3

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?

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

2 Comments

if I print x it says None. However I wanted it to return the source code.
sorry for that, you have to declare global inside the init function and not on the class declaration! I edited the answer, it works now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.