As others have pointed out, the second print
statment is executing because it's one of the suite of statements making up the class declaration -- all of which are executed when the module they're in is imported
because the declaration is part of its top-level code verses it being nested inside a function or method.
The first print
statement isn't executed because it's part of a method definition, whose statements don't execute until it's called --- unlike those within a class definition. Typically a class's __init__()
method is called indirectly when an instance of the class is created using the class's name, which would be d()
for one named d
like yours.
So, although it contradicts what's in the text of the strings being displayed, to make that second print
statement only execute when instances of the class are created (just like with the first one) you'd need to also make it part of the same method (or called by it). In other words, after doing so, neither of them will execute when the file the class is in is import
ed, but both will when any instances of the class are created. Here's what I mean:
File x.py
:
class d:
def __init__(self):
print 'print this will NOT be printed' # not true
print "this will be printed when object is created"
File b.py
:
import x # no print statements execute
obj = d() # both print statements will be executed now
__init__
like the other one? – Capuaprint
in the__init__
method? i think__init__
could be what you're looking for, since it is by definition the code is run on object creation – Munozclass d
's definition gets built (so you can call it fromB
), it executes the code inside of the class. Usually this means you'll have class-level variables set and unbound methods ready to be attached to instances, but in your case it means that statement will be printed. Someone better versed in Python than I can correct me/better state this :) – Roumell