0

Some conceptual doubts. In this code:

class A:
   print "here in A"

print "flying 1"

def main():
   print "here in main"

print "flying 2"

if __name__ == "__main__":
    main()
    print "another flying"

class B:
    print "flying/here in B"

    def __init__(self):
       print "built in B"

The output is as follows:

here in A
flying 1
flying 2
here in main
another flying
flying/here in B

Questions:

1.- Why "here in A" gets printed when there's no an instance of A? (no warning/error informed)

2.- What's the scope of the "flying" things? they all get printed. I don't understand the parsing rules of Python.

3.- Same as 1.- why "here in B" gets printed when there's no an instance of B?

4.- Is there something like a default class constructor?

Sorry for the confusion but a 'similar code' would never compile in, for example, C++

0

1 Answer 1

3

1: The print statements are run when the class is defined, the same way static class variables would be assigned without an instance being necessary. If you want them run only when an instance is created then put the statement withing the __init__ method, otherwise define another function within the class definition which an instance can call.

2: Python doesn't actually need a main() function like java and other languages, the whole file is run so the flying things are printed. The only parts that aren't run are within function definitions such as your "built in B".

3: See 1.

4: I'm not sure what you mean exactly but you might be referring to the object() constructor:

o = object() in Python is equivalent to

Object o = new Object(); in Java.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.