开发者

Python exception ordering

开发者 https://www.devze.com 2023-03-14 00:15 出处:网络
Just curious, why does the following code import sys class F(Exception): sys.stderr.write(\'Inside exception\\n\')

Just curious, why does the following code

import sys
class F(Exception):
    sys.stderr.write('Inside exception\n')
    sys.stderr.flush()
    pass

sys.stderr.write('Before Exception\n')
sys.stderr.flush()

try:
    raise F
except F:
    pass

output:

Inside exception
Before Exception

and not:

Before exception
Inside 开发者_开发问答Exception


You're printing in the class, not its initialization block . Try running this

import sys
class F(Exception):
    sys.stderr.write('Inside exception\n')
    sys.stderr.flush()
    pass

alone. i.e., it's not running when you call raise F. Try this instead

import sys
class F(Exception):
    def __init__():
        sys.stderr.write('Inside exception\n')
        sys.stderr.flush()

raise new F()


As Sven rightly said, class bodies are executed immediately when the class definition is executed.

In your code, your definition of your class F is above this command sys.stderr.write('Before Exception\n') and hence this sys.stderr.write('Inside exception\n') gets executed first and consequently its output is seen first.

As a test, run this program -

import sys

sys.stderr.write('Before Exception\n')
sys.stderr.flush()

class F(Exception):
    sys.stderr.write('Inside exception\n')
    sys.stderr.flush()
    pass

try:
    raise F
except F:
    pass

The output now you will get is -

Before exception
Inside Exception

This is simply because the statement sys.stderr.write('Before Exception\n') gets executed before the class definition gets executed.

Infact, the printing of Inside Exception has nothing to do with your initializing an instance of F (by using raise). It will get printed no matter you initialize an instance of F or not.

Try this -

import sys

class F(Exception):
    sys.stderr.write('Inside exception\n')
    sys.stderr.flush()
    pass

Still you will get this output -

Inside Exception

although you have not made an instance of the class F.


you have statements at the class level:

class F(Exception):
    sys.stderr.write('Inside exception\n')

consider this, which will not be executed until you create an object instance:

class F(Exception):
    def __init__(self):
        sys.stderr.write('Inside exception\n')
0

精彩评论

暂无评论...
验证码 换一张
取 消