For example, in the following code:
class test:
print "Hi"
Python would automatically print 'hi'. Sorry if this is an obvious question, but I can't find out why Python would do that unless a 'test' object was initiated. * I just started programming in general a few months ago and Python is my first language, so please spare some mercy on me.
You are building a class; the body of a class is executed as a function to build the definition. The local namespace of that 'function' forms the set of attributes that make up the class. See the class
statement documentation.
Methods in the class body are not executed; like function definitions, you need to call them first. But if you didn't first call the class body, you don't know what methods the class has, at all.
In the same way, any top-level code in a module is executed when you import a module, to form the module namespace. If you put print "Hi"
in a module, it is also executed immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With