Ravi Yadav
Ravi Yadav

Reputation: 405

Print statement in class getting executed even though there is no class instance/object

content of my python file

class myclass(object):
    def __init__(self):
        pass
    def myfun(self):
        pass
    print ("hello world")

Output on executing file

hello world

Query

since I did not create object of class . How's it still able to print "hello world" 

Upvotes: 3

Views: 662

Answers (2)

Jitesh Mohite
Jitesh Mohite

Reputation: 34210

It will get a call, as python work like that. Your code will always return output.

hello world

class myclass(object):
    def __init__(self):
        pass

    def myfun(self):
        print("hello world")
        pass

If you want to avoid it you have to add print statement inside the method.

Upvotes: 2

wim
wim

Reputation: 362717

The class body executes at class definition time, and that's how the language is designed.

From section 9.3.1 Class Definition syntax:

In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful.

That is simply how the execution model works in Python, so there's not much more to say about it.

as per my understanding...anything class can not run until we call it by creating a object

Simply a misunderstanding. This applies for def, i.e. function blocks, but not for class blocks.

Upvotes: 4

Related Questions