Neel
Neel

Reputation: 21253

Why inner class called in python

I have function where I declare class

>>> def a():
...     class A:
...         print "a"
...

When I call function, why it print a?

>>> a()
a

Upvotes: 0

Views: 59

Answers (3)

Miles
Miles

Reputation: 100

print "a" is executed when the class A(not the instance of A) is created, and a() is creating the class.

Generally, it's useful for setting class variables and such.

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

Because that's what you told it to do. There is nothing special about code written in a class block other than assignments will become attributes and normal functions defined within will be converted to methods. All other code just... executes.

Upvotes: 5

Tom Dalton
Tom Dalton

Reputation: 6190

print "a" is executed when the class is defined - which happens when you call the function.

Upvotes: 2

Related Questions