Наследование

In [1]:
class A:
    def f(self):
        print('A.f')

class B(A):
    def g(self):
        print('B.g')
        
class C(B):
    def f(self):
        print('C.f')
        
a = A()
b = B()
c = C()

type(a)
Out[1]:
__main__.A
In [2]:
type(a) is A
Out[2]:
True
In [3]:
type(b) is A
Out[3]:
False
In [4]:
isinstance(b, B)
Out[4]:
True
In [5]:
isinstance(b, A)
Out[5]:
True
In [6]:
isinstance(b, object)
Out[6]:
True
In [7]:
issubclass(C, A)
Out[7]:
True
In [8]:
issubclass(A, C)
Out[8]:
False
In [9]:
issubclass(A, object)
Out[9]:
True
In [10]:
c.__class__
Out[10]:
__main__.C
In [11]:
C.__bases__
Out[11]:
(__main__.B,)
In [12]:
A.__subclasses__()
Out[12]:
[__main__.B]
In [13]:
a.f()
A.f
In [14]:
b.f()
A.f
In [15]:
c.f()
C.f
In [16]:
C.__mro__
Out[16]:
(__main__.C, __main__.B, __main__.A, object)
In [17]:
c.lalala()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-9dfb942e242e> in <module>()
----> 1 c.lalala()

AttributeError: 'C' object has no attribute 'lalala'
In [ ]:
c.f()
In [ ]:
A.f(c)
In [ ]:
super(C, c).f()
In [18]:
class X:
    def __init__(self):
        print('X')

class Y(X):
    def __init__(self):
        super().__init__()
        print('Y')

y = Y()
X
Y

Обработка исключений

In [19]:
try:
    pass
except Exception as e:
    print('except Exception')
except ValueError as e:
    print('except ValueError')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
else
finally
In [20]:
try:
    raise Exception
except Exception as e:
    print('except Exception')
except ValueError as e:
    print('except ValueError')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
except Exception
finally
In [21]:
try:
    raise ValueError
except Exception as e:
    print('except Exception')
except ValueError as e:
    print('except ValueError')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
except Exception
finally
In [22]:
try:
    raise ValueError
except ValueError as e:
    print('except ValueError')
except Exception as e:
    print('except Exception')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
except ValueError
finally
In [23]:
try:
    raise Exception
except ValueError as e:
    print('except ValueError')
except Exception as e:
    print('except Exception')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
except Exception
finally
In [24]:
try:
    raise KeyboardInterrupt
except ValueError as e:
    print('except ValueError')
except Exception as e:
    print('except Exception')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
except
finally
In [25]:
try:
    raise ValueError
except ValueError as e:
    print('except ValueError')
    raise
except Exception as e:
    print('except Exception')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
except ValueError
finally
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-25-d14df5491728> in <module>()
      1 try:
----> 2     raise ValueError
      3 except ValueError as e:
      4     print('except ValueError')
      5     raise

ValueError: 
In [26]:
try:
    raise ValueError
except ValueError as e:
    print('except ValueError')
    raise RuntimeError from e
except Exception as e:
    print('except Exception')
except:
    print('except')
else:
    print('else')
finally:
    print('finally')
except ValueError
finally
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-26-530ad96889a8> in <module>()
      1 try:
----> 2     raise ValueError
      3 except ValueError as e:

ValueError: 

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
<ipython-input-26-530ad96889a8> in <module>()
      3 except ValueError as e:
      4     print('except ValueError')
----> 5     raise RuntimeError from e
      6 except Exception as e:
      7     print('except Exception')

RuntimeError: 
In [27]:
import sys
import traceback


try:
    raise KeyboardInterrupt
except ValueError as e:
    print('except ValueError')
    raise RuntimeError from e
except Exception as e:
    print('except Exception')
except:
    t, v, tb = sys.exc_info()
    print('except')
    traceback.print_exception(t, v, tb)
else:
    print('else')
finally:
    print('finally')
except
finally
Traceback (most recent call last):
  File "<ipython-input-27-a93c7b8bf6e4>", line 6, in <module>
    raise KeyboardInterrupt
KeyboardInterrupt
In [28]:
import traceback


try:
    raise KeyboardInterrupt
except ValueError as e:
    print('except ValueError')
    raise RuntimeError from e
except Exception as e:
    print('except Exception')
except:
    print('except')
    traceback.print_exc()
else:
    print('else')
finally:
    print('finally')
except
finally
Traceback (most recent call last):
  File "<ipython-input-28-c98ddb08fef6>", line 5, in <module>
    raise KeyboardInterrupt
KeyboardInterrupt
In [29]:
def f1():
    f2()

def f2():
    f3()
    
def f3():
    raise ValueError
    
f1()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-8be0b89f78dc> in <module>()
      8     raise ValueError
      9 
---> 10 f1()

<ipython-input-29-8be0b89f78dc> in f1()
      1 def f1():
----> 2     f2()
      3 
      4 def f2():
      5     f3()

<ipython-input-29-8be0b89f78dc> in f2()
      3 
      4 def f2():
----> 5     f3()
      6 
      7 def f3():

<ipython-input-29-8be0b89f78dc> in f3()
      6 
      7 def f3():
----> 8     raise ValueError
      9 
     10 f1()

ValueError: 
In [30]:
def f1():
    try:
        f2()
    except ValueError:
        print('gotcha')
    print('f1')

def f2():
    f3()
    print('f2')
    
def f3():
    raise ValueError
    print('f3')
    
f1()
gotcha
f1

Стандартные исключения

In [31]:
raise int
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-5edbdefb656d> in <module>()
----> 1 raise int

TypeError: exceptions must derive from BaseException
In [32]:
import sys

sys.exit()
An exception has occurred, use %tb to see the full traceback.

SystemExit
To exit: use 'exit', 'quit', or Ctrl-D.
In [33]:
import math

math.exp(1000)
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-33-07decbf21122> in <module>()
      1 import math
      2 
----> 3 math.exp(1000)

OverflowError: math range error
In [34]:
1 / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-34-b710d87c980c> in <module>()
----> 1 1 / 0

ZeroDivisionError: division by zero
In [35]:
assert(False)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-35-fa3f6d411be7> in <module>()
----> 1 assert(False)

AssertionError: 
In [36]:
"asdf".asdf
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-36-e35d4cd2873d> in <module>()
----> 1 "asdf".asdf

AttributeError: 'str' object has no attribute 'asdf'
In [37]:
import asdf
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-37-147c700235e1> in <module>()
----> 1 import asdf

ImportError: No module named 'asdf'
In [38]:
a = [1, 2, 3]
a[5]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-38-4a536f82b3e4> in <module>()
      1 a = [1, 2, 3]
----> 2 a[5]

IndexError: list index out of range
In [39]:
d = {}
d['a']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-39-f5351d7cf57c> in <module>()
      1 d = {}
----> 2 d['a']

KeyError: 'a'
In [40]:
a = list(range(10 ** 15))
---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
<ipython-input-40-3a844660094b> in <module>()
----> 1 a = list(range(10 ** 15))

MemoryError: 
In [41]:
def f():
    if False:
        a = 1
    print(a)
    
f()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-41-5d5ad679e519> in <module>()
      4     print(a)
      5 
----> 6 f()

<ipython-input-41-5d5ad679e519> in f()
      2     if False:
      3         a = 1
----> 4     print(a)
      5 
      6 f()

UnboundLocalError: local variable 'a' referenced before assignment
In [42]:
a +
  File "<ipython-input-42-8d389a9efe39>", line 1
    a +
       ^
SyntaxError: invalid syntax
In [43]:
def f():
    print(1)
      print(2)
  File "<ipython-input-43-1459426e007a>", line 3
    print(2)
    ^
IndentationError: unexpected indent
In [44]:
def f():
    print(1)
	print(2)
  File "<ipython-input-44-1e7c9f1412b2>", line 3
    print(2)
            ^
TabError: inconsistent use of tabs and spaces in indentation
In [45]:
"s" + 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-1c21f96a6344> in <module>()
----> 1 "s" + 1

TypeError: Can't convert 'int' object to str implicitly
In [46]:
import math

math.acos(2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-46-d017e0eda891> in <module>()
      1 import math
      2 
----> 3 math.acos(2)

ValueError: math domain error

Свое исключение

In [47]:
class MyError(Exception):
    def __init__(self, message):
        self.message = message

    def __str__(self):
        return self.message


raise MyError("Error message")
---------------------------------------------------------------------------
MyError                                   Traceback (most recent call last)
<ipython-input-47-45a4b93c7b3c> in <module>()
      7 
      8 
----> 9 raise MyError("Error message")

MyError: Error message