Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python import in __init__()

I need to have an import in __init__() method (because i need to run that import only when i instance the class).

But i cannot see that import outside __init__(), is the scope limited to__init__? how to do?

like image 681
tapioco123 Avatar asked Nov 15 '12 10:11

tapioco123


1 Answers

If you want the result of your import to be visible to other objects of the class, you would need to assign the resulting object from your import to a class or instance variable

For example:

>>> class Foo(object):
...    def __init__(self):
...       import math
...       self.bar = math.pi
...    def zoo(self):
...       return self.bar
... 
>>> a = Foo()
>>> a.zoo()
3.141592653589793
like image 73
Burhan Khalid Avatar answered Oct 02 '22 14:10

Burhan Khalid