Classes with exception

I was looking at the documentation on exceptions in python :-( https://docs.python.org/2/tutorial/classes.html#exceptions-are-classes-too )

I can not find how this code works

class B:
     pass
class C(B):
     pass
class D(C):
     pass  

for c in [B, C, D]:
    try:
        raise c()
    except D:
        print "D"
    except C:
        print "C"
    except B:
        print "B"

Conclusion: -

B
C
D

What happens in the classes? Just by going through the documentation that I can get, objects of all classes are created (the order of creating objects: - B, C and D), and exceptions are expressed in their names if this order then explains the output of B, C, D.

But if we replace "excpet" B with "except D", the whole result will be changed.

class B:
     pass
class C(B):
     pass
class D(C):
     pass  

for c in [B, C, D]:
    try:
        raise c()
    except B:
        print "B"
    except C:
        print "C"
    except D:
        print "D"

Conclusion: -

B
B
B

Now it makes my head spin: /

How does the order β€œexclude” a change in output?

I know that I have something missing from the documentation, perhaps because it is not very clear :(

+4
3

C D B, except B. except , , .

( ):

(-) except . try, . try , . , . , , ; . except , , "" . , , , , .

pass , , . class , docstring.

class B:
    """An exception that signals an error occurred"""

, docstring class, .

+8

except, , . , B, except B: , except .

pass - - . , -, Python . Java ++ / {}, Python it pass.

+1

It seems to me that the order of your exclusive statements is important, because Python will follow the logic of the first true exception that it sees.

In the first example, the first line of output will be B, because class B is not a subclass of C or D. In the second example, all output will be B, because each class is a subclass of B.

0
source

Source: https://habr.com/ru/post/1540533/


All Articles