Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a class get "called" when not initiated? - Python

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.

like image 668
SCE Avatar asked Jun 02 '13 18:06

SCE


1 Answers

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.

like image 133
Martijn Pieters Avatar answered Nov 14 '22 23:11

Martijn Pieters