Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing without executing the class - python

my problem is about i have a file that contain class and inside this class there is bunch of code will be executed

so whenever i import that file it will executed ! without creating an object of the class ! , here is the example

FILE X

class d:
    def __init__(self):
        print 'print this will NOT be printed'
    print "this will be printed"

file B

import x

output is this will be printed, so my question is how to skip executing it until creating a new object?

like image 786
Hamoudaq Avatar asked Aug 17 '12 17:08

Hamoudaq


1 Answers

You can't do that in Python, in Python every class is a first level object, a Python class is an object too and an class attribute can exist even if there is no instances of that class. If you just want to suppress the output of the print statement you can redirect the output of your print statements on the importing moment or create a context like the one provided in this first answer and use the __import__ statement manually.

like image 196
Tarantula Avatar answered Sep 20 '22 13:09

Tarantula