├── .gitignore ├── 000 └── ch_000.ipynb ├── 001 └── ch_001.ipynb ├── 002 ├── ch_002.ipynb ├── dict.ipynb └── 列表解析.ipynb ├── 003 ├── test.json └── 字符串.ipynb ├── 004 ├── 函数.ipynb └── 装饰器.ipynb ├── 005 ├── OOP-1.ipynb ├── OOP-2.ipynb └── OOP-3.ipynb ├── 006 ├── exc.py ├── key.py └── 异常处理.ipynb ├── 007 ├── bar.py ├── foo.py ├── m │ ├── __init__.py │ ├── bar.py │ ├── foo.py │ └── sub │ │ ├── __init__.py │ │ ├── sub │ │ ├── __init__.py │ │ └── y.py │ │ └── x.py ├── magedu_007.iml ├── main.py ├── requirments.txt ├── setup.py └── 模块化.ipynb ├── 008 ├── expr.py ├── heap.py ├── linklist.py ├── map.py ├── rule_parser.py ├── stack.py └── tree.py ├── Python编程基础.xmind ├── notes ├── .python-version ├── 20160221.adoc ├── 20160227-1.adoc ├── 20160227-2.adoc ├── 20160228.adoc ├── 20160305-1.adoc ├── 20160305-2.adoc └── 20160307.adoc ├── presentations ├── 000_环境准备.adoc ├── 001_基础语法.adoc ├── 002_内置容器.adoc ├── 003_字符串与文本操作.adoc ├── 004_函数.adoc └── 005_面向对象.adoc ├── property_classmethod.ipynb └── 复习.ipynb /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | .python-version 3 | .ipynb_checkpoints 4 | .idea 5 | .iml 6 | __pycache__ 7 | -------------------------------------------------------------------------------- /000/ch_000.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": false 8 | }, 9 | "outputs": [ 10 | { 11 | "name": "stdout", 12 | "output_type": "stream", 13 | "text": [ 14 | "test\n" 15 | ] 16 | } 17 | ], 18 | "source": [ 19 | "print('test')" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "# Hello world" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "metadata": { 33 | "collapsed": true 34 | }, 35 | "outputs": [], 36 | "source": [] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "julia R" 43 | ] 44 | } 45 | ], 46 | "metadata": { 47 | "kernelspec": { 48 | "display_name": "Python 3", 49 | "language": "python", 50 | "name": "python3" 51 | }, 52 | "language_info": { 53 | "codemirror_mode": { 54 | "name": "ipython", 55 | "version": 3 56 | }, 57 | "file_extension": ".py", 58 | "mimetype": "text/x-python", 59 | "name": "python", 60 | "nbconvert_exporter": "python", 61 | "pygments_lexer": "ipython3", 62 | "version": "3.4.2" 63 | } 64 | }, 65 | "nbformat": 4, 66 | "nbformat_minor": 0 67 | } 68 | -------------------------------------------------------------------------------- /001/ch_001.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Python基础语法" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## hello world" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "metadata": { 21 | "collapsed": false 22 | }, 23 | "outputs": [ 24 | { 25 | "name": "stdout", 26 | "output_type": "stream", 27 | "text": [ 28 | "hello world\n" 29 | ] 30 | } 31 | ], 32 | "source": [ 33 | "print('hello world')" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "metadata": {}, 39 | "source": [ 40 | "单独出现的字面常量无意义" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "metadata": { 47 | "collapsed": true 48 | }, 49 | "outputs": [], 50 | "source": [] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 2, 55 | "metadata": { 56 | "collapsed": false 57 | }, 58 | "outputs": [ 59 | { 60 | "data": { 61 | "text/plain": [ 62 | "'abc'" 63 | ] 64 | }, 65 | "execution_count": 2, 66 | "metadata": {}, 67 | "output_type": "execute_result" 68 | } 69 | ], 70 | "source": [ 71 | "3\n", 72 | "'abc'" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": {}, 78 | "source": [ 79 | "强类型" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": 3, 85 | "metadata": { 86 | "collapsed": false 87 | }, 88 | "outputs": [ 89 | { 90 | "ename": "TypeError", 91 | "evalue": "unsupported operand type(s) for +: 'int' and 'str'", 92 | "output_type": "error", 93 | "traceback": [ 94 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 95 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 96 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;36m1\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m'abc'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 97 | "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" 98 | ] 99 | } 100 | ], 101 | "source": [ 102 | "1 + 'abc'" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "metadata": {}, 108 | "source": [ 109 | "动态语言" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": 4, 115 | "metadata": { 116 | "collapsed": true 117 | }, 118 | "outputs": [], 119 | "source": [ 120 | "a = 1" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": 5, 126 | "metadata": { 127 | "collapsed": false 128 | }, 129 | "outputs": [ 130 | { 131 | "data": { 132 | "text/plain": [ 133 | "int" 134 | ] 135 | }, 136 | "execution_count": 5, 137 | "metadata": {}, 138 | "output_type": "execute_result" 139 | } 140 | ], 141 | "source": [ 142 | "type(a)" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 6, 148 | "metadata": { 149 | "collapsed": false 150 | }, 151 | "outputs": [ 152 | { 153 | "data": { 154 | "text/plain": [ 155 | "str" 156 | ] 157 | }, 158 | "execution_count": 6, 159 | "metadata": {}, 160 | "output_type": "execute_result" 161 | } 162 | ], 163 | "source": [ 164 | "a = 'abc'\n", 165 | "type(a)" 166 | ] 167 | }, 168 | { 169 | "cell_type": "markdown", 170 | "metadata": {}, 171 | "source": [ 172 | "原始类型" 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "metadata": {}, 178 | "source": [ 179 | "int float byte" 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": null, 185 | "metadata": { 186 | "collapsed": true 187 | }, 188 | "outputs": [], 189 | "source": [] 190 | }, 191 | { 192 | "cell_type": "markdown", 193 | "metadata": {}, 194 | "source": [ 195 | "复合类型" 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "metadata": {}, 201 | "source": [ 202 | "由其他原始类型组合起来的类型" 203 | ] 204 | }, 205 | { 206 | "cell_type": "markdown", 207 | "metadata": {}, 208 | "source": [ 209 | "list dict" 210 | ] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "metadata": {}, 215 | "source": [ 216 | "### 算术运算符" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 7, 222 | "metadata": { 223 | "collapsed": true 224 | }, 225 | "outputs": [], 226 | "source": [ 227 | "a = 10\n", 228 | "b = 20" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": 8, 234 | "metadata": { 235 | "collapsed": false 236 | }, 237 | "outputs": [ 238 | { 239 | "data": { 240 | "text/plain": [ 241 | "30" 242 | ] 243 | }, 244 | "execution_count": 8, 245 | "metadata": {}, 246 | "output_type": "execute_result" 247 | } 248 | ], 249 | "source": [ 250 | "a + b" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": 9, 256 | "metadata": { 257 | "collapsed": false 258 | }, 259 | "outputs": [ 260 | { 261 | "data": { 262 | "text/plain": [ 263 | "-10" 264 | ] 265 | }, 266 | "execution_count": 9, 267 | "metadata": {}, 268 | "output_type": "execute_result" 269 | } 270 | ], 271 | "source": [ 272 | "a - b" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 10, 278 | "metadata": { 279 | "collapsed": false 280 | }, 281 | "outputs": [ 282 | { 283 | "data": { 284 | "text/plain": [ 285 | "200" 286 | ] 287 | }, 288 | "execution_count": 10, 289 | "metadata": {}, 290 | "output_type": "execute_result" 291 | } 292 | ], 293 | "source": [ 294 | "a * b" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": 11, 300 | "metadata": { 301 | "collapsed": false 302 | }, 303 | "outputs": [ 304 | { 305 | "data": { 306 | "text/plain": [ 307 | "0.5" 308 | ] 309 | }, 310 | "execution_count": 11, 311 | "metadata": {}, 312 | "output_type": "execute_result" 313 | } 314 | ], 315 | "source": [ 316 | "a / b" 317 | ] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": 12, 322 | "metadata": { 323 | "collapsed": false 324 | }, 325 | "outputs": [ 326 | { 327 | "data": { 328 | "text/plain": [ 329 | "10" 330 | ] 331 | }, 332 | "execution_count": 12, 333 | "metadata": {}, 334 | "output_type": "execute_result" 335 | } 336 | ], 337 | "source": [ 338 | "a % b" 339 | ] 340 | }, 341 | { 342 | "cell_type": "code", 343 | "execution_count": 13, 344 | "metadata": { 345 | "collapsed": false 346 | }, 347 | "outputs": [ 348 | { 349 | "data": { 350 | "text/plain": [ 351 | "100000000000000000000" 352 | ] 353 | }, 354 | "execution_count": 13, 355 | "metadata": {}, 356 | "output_type": "execute_result" 357 | } 358 | ], 359 | "source": [ 360 | "a ** b" 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": 14, 366 | "metadata": { 367 | "collapsed": false 368 | }, 369 | "outputs": [ 370 | { 371 | "data": { 372 | "text/plain": [ 373 | "0" 374 | ] 375 | }, 376 | "execution_count": 14, 377 | "metadata": {}, 378 | "output_type": "execute_result" 379 | } 380 | ], 381 | "source": [ 382 | "a // b" 383 | ] 384 | }, 385 | { 386 | "cell_type": "markdown", 387 | "metadata": {}, 388 | "source": [ 389 | "### 位运算符" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": 15, 395 | "metadata": { 396 | "collapsed": false 397 | }, 398 | "outputs": [ 399 | { 400 | "data": { 401 | "text/plain": [ 402 | "'0b111100'" 403 | ] 404 | }, 405 | "execution_count": 15, 406 | "metadata": {}, 407 | "output_type": "execute_result" 408 | } 409 | ], 410 | "source": [ 411 | "bin(60)" 412 | ] 413 | }, 414 | { 415 | "cell_type": "code", 416 | "execution_count": 16, 417 | "metadata": { 418 | "collapsed": false 419 | }, 420 | "outputs": [ 421 | { 422 | "data": { 423 | "text/plain": [ 424 | "'0b1101'" 425 | ] 426 | }, 427 | "execution_count": 16, 428 | "metadata": {}, 429 | "output_type": "execute_result" 430 | } 431 | ], 432 | "source": [ 433 | "bin(13)" 434 | ] 435 | }, 436 | { 437 | "cell_type": "markdown", 438 | "metadata": {}, 439 | "source": [ 440 | "a = 0011 1100\n", 441 | "\n", 442 | "b = 0000 1101" 443 | ] 444 | }, 445 | { 446 | "cell_type": "code", 447 | "execution_count": null, 448 | "metadata": { 449 | "collapsed": true 450 | }, 451 | "outputs": [], 452 | "source": [] 453 | }, 454 | { 455 | "cell_type": "code", 456 | "execution_count": 17, 457 | "metadata": { 458 | "collapsed": true 459 | }, 460 | "outputs": [], 461 | "source": [ 462 | "a = 60\n", 463 | "b = 13" 464 | ] 465 | }, 466 | { 467 | "cell_type": "code", 468 | "execution_count": 18, 469 | "metadata": { 470 | "collapsed": false 471 | }, 472 | "outputs": [ 473 | { 474 | "data": { 475 | "text/plain": [ 476 | "12" 477 | ] 478 | }, 479 | "execution_count": 18, 480 | "metadata": {}, 481 | "output_type": "execute_result" 482 | } 483 | ], 484 | "source": [ 485 | "a & b" 486 | ] 487 | }, 488 | { 489 | "cell_type": "markdown", 490 | "metadata": {}, 491 | "source": [ 492 | "0011 1100\n", 493 | "\n", 494 | "0000 1101\n", 495 | "\n", 496 | "\n", 497 | "0000 1100" 498 | ] 499 | }, 500 | { 501 | "cell_type": "code", 502 | "execution_count": 19, 503 | "metadata": { 504 | "collapsed": false 505 | }, 506 | "outputs": [ 507 | { 508 | "data": { 509 | "text/plain": [ 510 | "12" 511 | ] 512 | }, 513 | "execution_count": 19, 514 | "metadata": {}, 515 | "output_type": "execute_result" 516 | } 517 | ], 518 | "source": [ 519 | "int('1100', 2)" 520 | ] 521 | }, 522 | { 523 | "cell_type": "code", 524 | "execution_count": 20, 525 | "metadata": { 526 | "collapsed": false 527 | }, 528 | "outputs": [ 529 | { 530 | "data": { 531 | "text/plain": [ 532 | "61" 533 | ] 534 | }, 535 | "execution_count": 20, 536 | "metadata": {}, 537 | "output_type": "execute_result" 538 | } 539 | ], 540 | "source": [ 541 | "a | b" 542 | ] 543 | }, 544 | { 545 | "cell_type": "markdown", 546 | "metadata": {}, 547 | "source": [ 548 | "0011 1100\n", 549 | "\n", 550 | "0000 1101\n", 551 | "\n", 552 | "0011 1101" 553 | ] 554 | }, 555 | { 556 | "cell_type": "code", 557 | "execution_count": 21, 558 | "metadata": { 559 | "collapsed": false 560 | }, 561 | "outputs": [ 562 | { 563 | "ename": "TypeError", 564 | "evalue": "bin() takes exactly one argument (2 given)", 565 | "output_type": "error", 566 | "traceback": [ 567 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 568 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 569 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mbin\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'111101'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 570 | "\u001b[0;31mTypeError\u001b[0m: bin() takes exactly one argument (2 given)" 571 | ] 572 | } 573 | ], 574 | "source": [ 575 | "bin('111101', 2)" 576 | ] 577 | }, 578 | { 579 | "cell_type": "code", 580 | "execution_count": 22, 581 | "metadata": { 582 | "collapsed": false 583 | }, 584 | "outputs": [ 585 | { 586 | "data": { 587 | "text/plain": [ 588 | "61" 589 | ] 590 | }, 591 | "execution_count": 22, 592 | "metadata": {}, 593 | "output_type": "execute_result" 594 | } 595 | ], 596 | "source": [ 597 | "int('111101', 2)" 598 | ] 599 | }, 600 | { 601 | "cell_type": "code", 602 | "execution_count": 23, 603 | "metadata": { 604 | "collapsed": false 605 | }, 606 | "outputs": [ 607 | { 608 | "data": { 609 | "text/plain": [ 610 | "49" 611 | ] 612 | }, 613 | "execution_count": 23, 614 | "metadata": {}, 615 | "output_type": "execute_result" 616 | } 617 | ], 618 | "source": [ 619 | "a ^ b" 620 | ] 621 | }, 622 | { 623 | "cell_type": "markdown", 624 | "metadata": {}, 625 | "source": [ 626 | "0011 1100\n", 627 | "\n", 628 | "0000 1101\n", 629 | "\n", 630 | "0011 0001" 631 | ] 632 | }, 633 | { 634 | "cell_type": "code", 635 | "execution_count": 24, 636 | "metadata": { 637 | "collapsed": false 638 | }, 639 | "outputs": [ 640 | { 641 | "data": { 642 | "text/plain": [ 643 | "49" 644 | ] 645 | }, 646 | "execution_count": 24, 647 | "metadata": {}, 648 | "output_type": "execute_result" 649 | } 650 | ], 651 | "source": [ 652 | "int('110001', 2)" 653 | ] 654 | }, 655 | { 656 | "cell_type": "code", 657 | "execution_count": 25, 658 | "metadata": { 659 | "collapsed": false 660 | }, 661 | "outputs": [ 662 | { 663 | "data": { 664 | "text/plain": [ 665 | "-61" 666 | ] 667 | }, 668 | "execution_count": 25, 669 | "metadata": {}, 670 | "output_type": "execute_result" 671 | } 672 | ], 673 | "source": [ 674 | "~a" 675 | ] 676 | }, 677 | { 678 | "cell_type": "markdown", 679 | "metadata": {}, 680 | "source": [ 681 | "0011 1100\n", 682 | "\n", 683 | "1100 0011" 684 | ] 685 | }, 686 | { 687 | "cell_type": "code", 688 | "execution_count": 26, 689 | "metadata": { 690 | "collapsed": false 691 | }, 692 | "outputs": [ 693 | { 694 | "data": { 695 | "text/plain": [ 696 | "195" 697 | ] 698 | }, 699 | "execution_count": 26, 700 | "metadata": {}, 701 | "output_type": "execute_result" 702 | } 703 | ], 704 | "source": [ 705 | "int('11000011',2)" 706 | ] 707 | }, 708 | { 709 | "cell_type": "code", 710 | "execution_count": 27, 711 | "metadata": { 712 | "collapsed": false 713 | }, 714 | "outputs": [ 715 | { 716 | "data": { 717 | "text/plain": [ 718 | "67" 719 | ] 720 | }, 721 | "execution_count": 27, 722 | "metadata": {}, 723 | "output_type": "execute_result" 724 | } 725 | ], 726 | "source": [ 727 | "int('1000011', 2)" 728 | ] 729 | }, 730 | { 731 | "cell_type": "markdown", 732 | "metadata": {}, 733 | "source": [ 734 | "## 比较运算符" 735 | ] 736 | }, 737 | { 738 | "cell_type": "code", 739 | "execution_count": 28, 740 | "metadata": { 741 | "collapsed": true 742 | }, 743 | "outputs": [], 744 | "source": [ 745 | "a = 10\n", 746 | "b = 20" 747 | ] 748 | }, 749 | { 750 | "cell_type": "code", 751 | "execution_count": 29, 752 | "metadata": { 753 | "collapsed": false 754 | }, 755 | "outputs": [ 756 | { 757 | "data": { 758 | "text/plain": [ 759 | "False" 760 | ] 761 | }, 762 | "execution_count": 29, 763 | "metadata": {}, 764 | "output_type": "execute_result" 765 | } 766 | ], 767 | "source": [ 768 | "a == b" 769 | ] 770 | }, 771 | { 772 | "cell_type": "code", 773 | "execution_count": 30, 774 | "metadata": { 775 | "collapsed": false 776 | }, 777 | "outputs": [ 778 | { 779 | "data": { 780 | "text/plain": [ 781 | "True" 782 | ] 783 | }, 784 | "execution_count": 30, 785 | "metadata": {}, 786 | "output_type": "execute_result" 787 | } 788 | ], 789 | "source": [ 790 | "a != b" 791 | ] 792 | }, 793 | { 794 | "cell_type": "code", 795 | "execution_count": 31, 796 | "metadata": { 797 | "collapsed": false 798 | }, 799 | "outputs": [ 800 | { 801 | "data": { 802 | "text/plain": [ 803 | "True" 804 | ] 805 | }, 806 | "execution_count": 31, 807 | "metadata": {}, 808 | "output_type": "execute_result" 809 | } 810 | ], 811 | "source": [ 812 | "a < b" 813 | ] 814 | }, 815 | { 816 | "cell_type": "code", 817 | "execution_count": 32, 818 | "metadata": { 819 | "collapsed": false 820 | }, 821 | "outputs": [ 822 | { 823 | "data": { 824 | "text/plain": [ 825 | "False" 826 | ] 827 | }, 828 | "execution_count": 32, 829 | "metadata": {}, 830 | "output_type": "execute_result" 831 | } 832 | ], 833 | "source": [ 834 | "a > b" 835 | ] 836 | }, 837 | { 838 | "cell_type": "code", 839 | "execution_count": 33, 840 | "metadata": { 841 | "collapsed": false 842 | }, 843 | "outputs": [ 844 | { 845 | "data": { 846 | "text/plain": [ 847 | "True" 848 | ] 849 | }, 850 | "execution_count": 33, 851 | "metadata": {}, 852 | "output_type": "execute_result" 853 | } 854 | ], 855 | "source": [ 856 | "a <= b" 857 | ] 858 | }, 859 | { 860 | "cell_type": "code", 861 | "execution_count": 34, 862 | "metadata": { 863 | "collapsed": false 864 | }, 865 | "outputs": [ 866 | { 867 | "data": { 868 | "text/plain": [ 869 | "False" 870 | ] 871 | }, 872 | "execution_count": 34, 873 | "metadata": {}, 874 | "output_type": "execute_result" 875 | } 876 | ], 877 | "source": [ 878 | "a >= b" 879 | ] 880 | }, 881 | { 882 | "cell_type": "markdown", 883 | "metadata": {}, 884 | "source": [ 885 | "### 逻辑运算符" 886 | ] 887 | }, 888 | { 889 | "cell_type": "code", 890 | "execution_count": 35, 891 | "metadata": { 892 | "collapsed": true 893 | }, 894 | "outputs": [], 895 | "source": [ 896 | "a = True\n", 897 | "b = False" 898 | ] 899 | }, 900 | { 901 | "cell_type": "code", 902 | "execution_count": 36, 903 | "metadata": { 904 | "collapsed": false 905 | }, 906 | "outputs": [ 907 | { 908 | "data": { 909 | "text/plain": [ 910 | "False" 911 | ] 912 | }, 913 | "execution_count": 36, 914 | "metadata": {}, 915 | "output_type": "execute_result" 916 | } 917 | ], 918 | "source": [ 919 | "a and b" 920 | ] 921 | }, 922 | { 923 | "cell_type": "code", 924 | "execution_count": 37, 925 | "metadata": { 926 | "collapsed": false 927 | }, 928 | "outputs": [ 929 | { 930 | "data": { 931 | "text/plain": [ 932 | "True" 933 | ] 934 | }, 935 | "execution_count": 37, 936 | "metadata": {}, 937 | "output_type": "execute_result" 938 | } 939 | ], 940 | "source": [ 941 | "a or b" 942 | ] 943 | }, 944 | { 945 | "cell_type": "code", 946 | "execution_count": 38, 947 | "metadata": { 948 | "collapsed": false 949 | }, 950 | "outputs": [ 951 | { 952 | "data": { 953 | "text/plain": [ 954 | "False" 955 | ] 956 | }, 957 | "execution_count": 38, 958 | "metadata": {}, 959 | "output_type": "execute_result" 960 | } 961 | ], 962 | "source": [ 963 | "not a" 964 | ] 965 | }, 966 | { 967 | "cell_type": "markdown", 968 | "metadata": {}, 969 | "source": [ 970 | "* 逻辑运算符的短路功能" 971 | ] 972 | }, 973 | { 974 | "cell_type": "code", 975 | "execution_count": 39, 976 | "metadata": { 977 | "collapsed": false 978 | }, 979 | "outputs": [ 980 | { 981 | "name": "stdout", 982 | "output_type": "stream", 983 | "text": [ 984 | "1 + 2\n" 985 | ] 986 | }, 987 | { 988 | "data": { 989 | "text/plain": [ 990 | "False" 991 | ] 992 | }, 993 | "execution_count": 39, 994 | "metadata": {}, 995 | "output_type": "execute_result" 996 | } 997 | ], 998 | "source": [ 999 | "def add(x, y):\n", 1000 | " print(\"%d + %d\" % (x, y))\n", 1001 | " return x+y\n", 1002 | "\n", 1003 | "add(1, 2) > 4 and add(2, 3) == 5" 1004 | ] 1005 | }, 1006 | { 1007 | "cell_type": "code", 1008 | "execution_count": 40, 1009 | "metadata": { 1010 | "collapsed": false 1011 | }, 1012 | "outputs": [ 1013 | { 1014 | "name": "stdout", 1015 | "output_type": "stream", 1016 | "text": [ 1017 | "2 + 3\n" 1018 | ] 1019 | }, 1020 | { 1021 | "data": { 1022 | "text/plain": [ 1023 | "True" 1024 | ] 1025 | }, 1026 | "execution_count": 40, 1027 | "metadata": {}, 1028 | "output_type": "execute_result" 1029 | } 1030 | ], 1031 | "source": [ 1032 | "add(2, 3) == 5 or add(1, 2) > 4" 1033 | ] 1034 | }, 1035 | { 1036 | "cell_type": "markdown", 1037 | "metadata": {}, 1038 | "source": [ 1039 | "### 其他运算符" 1040 | ] 1041 | }, 1042 | { 1043 | "cell_type": "code", 1044 | "execution_count": 41, 1045 | "metadata": { 1046 | "collapsed": false 1047 | }, 1048 | "outputs": [ 1049 | { 1050 | "data": { 1051 | "text/plain": [ 1052 | "False" 1053 | ] 1054 | }, 1055 | "execution_count": 41, 1056 | "metadata": {}, 1057 | "output_type": "execute_result" 1058 | } 1059 | ], 1060 | "source": [ 1061 | "b" 1062 | ] 1063 | }, 1064 | { 1065 | "cell_type": "code", 1066 | "execution_count": 42, 1067 | "metadata": { 1068 | "collapsed": true 1069 | }, 1070 | "outputs": [], 1071 | "source": [ 1072 | "a = b" 1073 | ] 1074 | }, 1075 | { 1076 | "cell_type": "code", 1077 | "execution_count": 43, 1078 | "metadata": { 1079 | "collapsed": false 1080 | }, 1081 | "outputs": [ 1082 | { 1083 | "data": { 1084 | "text/plain": [ 1085 | "False" 1086 | ] 1087 | }, 1088 | "execution_count": 43, 1089 | "metadata": {}, 1090 | "output_type": "execute_result" 1091 | } 1092 | ], 1093 | "source": [ 1094 | "a" 1095 | ] 1096 | }, 1097 | { 1098 | "cell_type": "markdown", 1099 | "metadata": {}, 1100 | "source": [ 1101 | "`is` vs `==`" 1102 | ] 1103 | }, 1104 | { 1105 | "cell_type": "code", 1106 | "execution_count": 44, 1107 | "metadata": { 1108 | "collapsed": false 1109 | }, 1110 | "outputs": [ 1111 | { 1112 | "data": { 1113 | "text/plain": [ 1114 | "True" 1115 | ] 1116 | }, 1117 | "execution_count": 44, 1118 | "metadata": {}, 1119 | "output_type": "execute_result" 1120 | } 1121 | ], 1122 | "source": [ 1123 | "1000 == 1000" 1124 | ] 1125 | }, 1126 | { 1127 | "cell_type": "code", 1128 | "execution_count": 45, 1129 | "metadata": { 1130 | "collapsed": false 1131 | }, 1132 | "outputs": [ 1133 | { 1134 | "data": { 1135 | "text/plain": [ 1136 | "True" 1137 | ] 1138 | }, 1139 | "execution_count": 45, 1140 | "metadata": {}, 1141 | "output_type": "execute_result" 1142 | } 1143 | ], 1144 | "source": [ 1145 | "1000 is 1000" 1146 | ] 1147 | }, 1148 | { 1149 | "cell_type": "code", 1150 | "execution_count": 46, 1151 | "metadata": { 1152 | "collapsed": false 1153 | }, 1154 | "outputs": [ 1155 | { 1156 | "data": { 1157 | "text/plain": [ 1158 | "True" 1159 | ] 1160 | }, 1161 | "execution_count": 46, 1162 | "metadata": {}, 1163 | "output_type": "execute_result" 1164 | } 1165 | ], 1166 | "source": [ 1167 | "[1, 2, 3] == [1, 2, 3]" 1168 | ] 1169 | }, 1170 | { 1171 | "cell_type": "code", 1172 | "execution_count": 47, 1173 | "metadata": { 1174 | "collapsed": false 1175 | }, 1176 | "outputs": [ 1177 | { 1178 | "data": { 1179 | "text/plain": [ 1180 | "False" 1181 | ] 1182 | }, 1183 | "execution_count": 47, 1184 | "metadata": {}, 1185 | "output_type": "execute_result" 1186 | } 1187 | ], 1188 | "source": [ 1189 | "[1, 2, 3] is [1, 2, 3]" 1190 | ] 1191 | }, 1192 | { 1193 | "cell_type": "code", 1194 | "execution_count": 48, 1195 | "metadata": { 1196 | "collapsed": false 1197 | }, 1198 | "outputs": [ 1199 | { 1200 | "data": { 1201 | "text/plain": [ 1202 | "4505415432" 1203 | ] 1204 | }, 1205 | "execution_count": 48, 1206 | "metadata": {}, 1207 | "output_type": "execute_result" 1208 | } 1209 | ], 1210 | "source": [ 1211 | "id([1, 2, 3])" 1212 | ] 1213 | }, 1214 | { 1215 | "cell_type": "code", 1216 | "execution_count": 49, 1217 | "metadata": { 1218 | "collapsed": false 1219 | }, 1220 | "outputs": [ 1221 | { 1222 | "data": { 1223 | "text/plain": [ 1224 | "4505415944" 1225 | ] 1226 | }, 1227 | "execution_count": 49, 1228 | "metadata": {}, 1229 | "output_type": "execute_result" 1230 | } 1231 | ], 1232 | "source": [ 1233 | "id([1, 2, 3])" 1234 | ] 1235 | }, 1236 | { 1237 | "cell_type": "code", 1238 | "execution_count": 50, 1239 | "metadata": { 1240 | "collapsed": false 1241 | }, 1242 | "outputs": [ 1243 | { 1244 | "data": { 1245 | "text/plain": [ 1246 | "4504861488" 1247 | ] 1248 | }, 1249 | "execution_count": 50, 1250 | "metadata": {}, 1251 | "output_type": "execute_result" 1252 | } 1253 | ], 1254 | "source": [ 1255 | "id(1000)" 1256 | ] 1257 | }, 1258 | { 1259 | "cell_type": "code", 1260 | "execution_count": 51, 1261 | "metadata": { 1262 | "collapsed": false 1263 | }, 1264 | "outputs": [ 1265 | { 1266 | "data": { 1267 | "text/plain": [ 1268 | "4504861648" 1269 | ] 1270 | }, 1271 | "execution_count": 51, 1272 | "metadata": {}, 1273 | "output_type": "execute_result" 1274 | } 1275 | ], 1276 | "source": [ 1277 | "id(1000)" 1278 | ] 1279 | }, 1280 | { 1281 | "cell_type": "code", 1282 | "execution_count": 52, 1283 | "metadata": { 1284 | "collapsed": false 1285 | }, 1286 | "outputs": [ 1287 | { 1288 | "ename": "SyntaxError", 1289 | "evalue": "invalid syntax (, line 1)", 1290 | "output_type": "error", 1291 | "traceback": [ 1292 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m is None\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" 1293 | ] 1294 | } 1295 | ], 1296 | "source": [ 1297 | "is None" 1298 | ] 1299 | }, 1300 | { 1301 | "cell_type": "markdown", 1302 | "metadata": {}, 1303 | "source": [ 1304 | "表达式" 1305 | ] 1306 | }, 1307 | { 1308 | "cell_type": "code", 1309 | "execution_count": 53, 1310 | "metadata": { 1311 | "collapsed": false 1312 | }, 1313 | "outputs": [ 1314 | { 1315 | "data": { 1316 | "text/plain": [ 1317 | "False" 1318 | ] 1319 | }, 1320 | "execution_count": 53, 1321 | "metadata": {}, 1322 | "output_type": "execute_result" 1323 | } 1324 | ], 1325 | "source": [ 1326 | "a" 1327 | ] 1328 | }, 1329 | { 1330 | "cell_type": "code", 1331 | "execution_count": 54, 1332 | "metadata": { 1333 | "collapsed": false 1334 | }, 1335 | "outputs": [ 1336 | { 1337 | "data": { 1338 | "text/plain": [ 1339 | "False" 1340 | ] 1341 | }, 1342 | "execution_count": 54, 1343 | "metadata": {}, 1344 | "output_type": "execute_result" 1345 | } 1346 | ], 1347 | "source": [ 1348 | "a and (1+2) < 3 " 1349 | ] 1350 | }, 1351 | { 1352 | "cell_type": "code", 1353 | "execution_count": 55, 1354 | "metadata": { 1355 | "collapsed": true 1356 | }, 1357 | "outputs": [], 1358 | "source": [ 1359 | "a = 4" 1360 | ] 1361 | }, 1362 | { 1363 | "cell_type": "code", 1364 | "execution_count": 56, 1365 | "metadata": { 1366 | "collapsed": false 1367 | }, 1368 | "outputs": [ 1369 | { 1370 | "data": { 1371 | "text/plain": [ 1372 | "4" 1373 | ] 1374 | }, 1375 | "execution_count": 56, 1376 | "metadata": {}, 1377 | "output_type": "execute_result" 1378 | } 1379 | ], 1380 | "source": [ 1381 | "a if a > 0 else 0" 1382 | ] 1383 | }, 1384 | { 1385 | "cell_type": "code", 1386 | "execution_count": 57, 1387 | "metadata": { 1388 | "collapsed": false 1389 | }, 1390 | "outputs": [ 1391 | { 1392 | "name": "stdout", 1393 | "output_type": "stream", 1394 | "text": [ 1395 | "a\n", 1396 | "b\n" 1397 | ] 1398 | } 1399 | ], 1400 | "source": [ 1401 | "if True:\n", 1402 | " print('a')\n", 1403 | " print('b')" 1404 | ] 1405 | }, 1406 | { 1407 | "cell_type": "code", 1408 | "execution_count": 58, 1409 | "metadata": { 1410 | "collapsed": true 1411 | }, 1412 | "outputs": [], 1413 | "source": [ 1414 | "if False:\n", 1415 | " print('flase')" 1416 | ] 1417 | }, 1418 | { 1419 | "cell_type": "code", 1420 | "execution_count": 63, 1421 | "metadata": { 1422 | "collapsed": true 1423 | }, 1424 | "outputs": [], 1425 | "source": [ 1426 | "a = -4" 1427 | ] 1428 | }, 1429 | { 1430 | "cell_type": "code", 1431 | "execution_count": null, 1432 | "metadata": { 1433 | "collapsed": true 1434 | }, 1435 | "outputs": [], 1436 | "source": [] 1437 | }, 1438 | { 1439 | "cell_type": "code", 1440 | "execution_count": 64, 1441 | "metadata": { 1442 | "collapsed": true 1443 | }, 1444 | "outputs": [], 1445 | "source": [ 1446 | "if a > 0:\n", 1447 | " a = 5\n", 1448 | "else:\n", 1449 | " a = 0" 1450 | ] 1451 | }, 1452 | { 1453 | "cell_type": "code", 1454 | "execution_count": 65, 1455 | "metadata": { 1456 | "collapsed": false 1457 | }, 1458 | "outputs": [ 1459 | { 1460 | "data": { 1461 | "text/plain": [ 1462 | "0" 1463 | ] 1464 | }, 1465 | "execution_count": 65, 1466 | "metadata": {}, 1467 | "output_type": "execute_result" 1468 | } 1469 | ], 1470 | "source": [ 1471 | "a" 1472 | ] 1473 | }, 1474 | { 1475 | "cell_type": "code", 1476 | "execution_count": null, 1477 | "metadata": { 1478 | "collapsed": true 1479 | }, 1480 | "outputs": [], 1481 | "source": [] 1482 | }, 1483 | { 1484 | "cell_type": "code", 1485 | "execution_count": 62, 1486 | "metadata": { 1487 | "collapsed": false 1488 | }, 1489 | "outputs": [ 1490 | { 1491 | "data": { 1492 | "text/plain": [ 1493 | "5" 1494 | ] 1495 | }, 1496 | "execution_count": 62, 1497 | "metadata": {}, 1498 | "output_type": "execute_result" 1499 | } 1500 | ], 1501 | "source": [ 1502 | "a" 1503 | ] 1504 | }, 1505 | { 1506 | "cell_type": "code", 1507 | "execution_count": null, 1508 | "metadata": { 1509 | "collapsed": true 1510 | }, 1511 | "outputs": [], 1512 | "source": [] 1513 | }, 1514 | { 1515 | "cell_type": "code", 1516 | "execution_count": 66, 1517 | "metadata": { 1518 | "collapsed": false 1519 | }, 1520 | "outputs": [ 1521 | { 1522 | "name": "stdout", 1523 | "output_type": "stream", 1524 | "text": [ 1525 | "a > 0\n" 1526 | ] 1527 | } 1528 | ], 1529 | "source": [ 1530 | "a = 4\n", 1531 | "if a > 5:\n", 1532 | " print('a > 5')\n", 1533 | "elif a > 0:\n", 1534 | " print('a > 0')\n", 1535 | "else:\n", 1536 | " print('a < 0')" 1537 | ] 1538 | }, 1539 | { 1540 | "cell_type": "code", 1541 | "execution_count": 67, 1542 | "metadata": { 1543 | "collapsed": false 1544 | }, 1545 | "outputs": [ 1546 | { 1547 | "name": "stdout", 1548 | "output_type": "stream", 1549 | "text": [ 1550 | "a > 0\n" 1551 | ] 1552 | } 1553 | ], 1554 | "source": [ 1555 | "a = 4\n", 1556 | "if a > 5:\n", 1557 | " print('a > 5')\n", 1558 | "else:\n", 1559 | " if a > 0:\n", 1560 | " print('a > 0')\n", 1561 | " else:\n", 1562 | " print('a < 0')" 1563 | ] 1564 | }, 1565 | { 1566 | "cell_type": "code", 1567 | "execution_count": 68, 1568 | "metadata": { 1569 | "collapsed": false 1570 | }, 1571 | "outputs": [ 1572 | { 1573 | "name": "stdout", 1574 | "output_type": "stream", 1575 | "text": [ 1576 | "4\n", 1577 | "3\n", 1578 | "2\n", 1579 | "1\n" 1580 | ] 1581 | } 1582 | ], 1583 | "source": [ 1584 | "a = 4\n", 1585 | "while a > 0:\n", 1586 | " print(a)\n", 1587 | " a -= 1" 1588 | ] 1589 | }, 1590 | { 1591 | "cell_type": "code", 1592 | "execution_count": 69, 1593 | "metadata": { 1594 | "collapsed": false 1595 | }, 1596 | "outputs": [ 1597 | { 1598 | "name": "stdout", 1599 | "output_type": "stream", 1600 | "text": [ 1601 | "1\n", 1602 | "2\n", 1603 | "3\n", 1604 | "4\n" 1605 | ] 1606 | } 1607 | ], 1608 | "source": [ 1609 | "li = [1, 2, 3, 4]\n", 1610 | "for i in li:\n", 1611 | " print(i)\n", 1612 | " " 1613 | ] 1614 | }, 1615 | { 1616 | "cell_type": "code", 1617 | "execution_count": 1, 1618 | "metadata": { 1619 | "collapsed": false 1620 | }, 1621 | "outputs": [ 1622 | { 1623 | "data": { 1624 | "text/plain": [ 1625 | "range(0, 10)" 1626 | ] 1627 | }, 1628 | "execution_count": 1, 1629 | "metadata": {}, 1630 | "output_type": "execute_result" 1631 | } 1632 | ], 1633 | "source": [ 1634 | "range(10)" 1635 | ] 1636 | }, 1637 | { 1638 | "cell_type": "code", 1639 | "execution_count": 2, 1640 | "metadata": { 1641 | "collapsed": true 1642 | }, 1643 | "outputs": [], 1644 | "source": [ 1645 | "r = range(10)" 1646 | ] 1647 | }, 1648 | { 1649 | "cell_type": "code", 1650 | "execution_count": 3, 1651 | "metadata": { 1652 | "collapsed": false 1653 | }, 1654 | "outputs": [ 1655 | { 1656 | "ename": "TypeError", 1657 | "evalue": "'range' object is not an iterator", 1658 | "output_type": "error", 1659 | "traceback": [ 1660 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 1661 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 1662 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mr\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 1663 | "\u001b[0;31mTypeError\u001b[0m: 'range' object is not an iterator" 1664 | ] 1665 | } 1666 | ], 1667 | "source": [ 1668 | "next(r)" 1669 | ] 1670 | }, 1671 | { 1672 | "cell_type": "code", 1673 | "execution_count": 4, 1674 | "metadata": { 1675 | "collapsed": false 1676 | }, 1677 | "outputs": [ 1678 | { 1679 | "data": { 1680 | "text/plain": [ 1681 | "" 1682 | ] 1683 | }, 1684 | "execution_count": 4, 1685 | "metadata": {}, 1686 | "output_type": "execute_result" 1687 | } 1688 | ], 1689 | "source": [ 1690 | "iter(r)" 1691 | ] 1692 | }, 1693 | { 1694 | "cell_type": "code", 1695 | "execution_count": 5, 1696 | "metadata": { 1697 | "collapsed": false 1698 | }, 1699 | "outputs": [ 1700 | { 1701 | "data": { 1702 | "text/plain": [ 1703 | "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" 1704 | ] 1705 | }, 1706 | "execution_count": 5, 1707 | "metadata": {}, 1708 | "output_type": "execute_result" 1709 | } 1710 | ], 1711 | "source": [ 1712 | "list(range(10))" 1713 | ] 1714 | }, 1715 | { 1716 | "cell_type": "code", 1717 | "execution_count": 6, 1718 | "metadata": { 1719 | "collapsed": false 1720 | }, 1721 | "outputs": [ 1722 | { 1723 | "data": { 1724 | "text/plain": [ 1725 | "[5, 6, 7, 8, 9]" 1726 | ] 1727 | }, 1728 | "execution_count": 6, 1729 | "metadata": {}, 1730 | "output_type": "execute_result" 1731 | } 1732 | ], 1733 | "source": [ 1734 | "list(range(5, 10))" 1735 | ] 1736 | }, 1737 | { 1738 | "cell_type": "code", 1739 | "execution_count": 7, 1740 | "metadata": { 1741 | "collapsed": false 1742 | }, 1743 | "outputs": [ 1744 | { 1745 | "data": { 1746 | "text/plain": [ 1747 | "[0, 2, 4, 6, 8]" 1748 | ] 1749 | }, 1750 | "execution_count": 7, 1751 | "metadata": {}, 1752 | "output_type": "execute_result" 1753 | } 1754 | ], 1755 | "source": [ 1756 | "list(range(0, 10, 2))" 1757 | ] 1758 | }, 1759 | { 1760 | "cell_type": "code", 1761 | "execution_count": 9, 1762 | "metadata": { 1763 | "collapsed": false 1764 | }, 1765 | "outputs": [ 1766 | { 1767 | "name": "stdout", 1768 | "output_type": "stream", 1769 | "text": [ 1770 | "0\n", 1771 | "1\n", 1772 | "2\n", 1773 | "3\n", 1774 | "4\n", 1775 | "5\n", 1776 | "6\n" 1777 | ] 1778 | } 1779 | ], 1780 | "source": [ 1781 | "for x in range(10):\n", 1782 | " print(x)\n", 1783 | " if x > 5:\n", 1784 | " break" 1785 | ] 1786 | }, 1787 | { 1788 | "cell_type": "code", 1789 | "execution_count": 10, 1790 | "metadata": { 1791 | "collapsed": false 1792 | }, 1793 | "outputs": [ 1794 | { 1795 | "name": "stdout", 1796 | "output_type": "stream", 1797 | "text": [ 1798 | "0\n", 1799 | "\t 0\n", 1800 | "\t 1\n", 1801 | "\t 2\n", 1802 | "\t 3\n", 1803 | "1\n", 1804 | "\t 0\n", 1805 | "\t 1\n", 1806 | "\t 2\n", 1807 | "\t 3\n", 1808 | "2\n", 1809 | "\t 0\n", 1810 | "\t 1\n", 1811 | "\t 2\n", 1812 | "\t 3\n" 1813 | ] 1814 | } 1815 | ], 1816 | "source": [ 1817 | "for x in range(3):\n", 1818 | " print(x)\n", 1819 | " for i in range(5):\n", 1820 | " print('\\t %d' % i)\n", 1821 | " if i > 2:\n", 1822 | " break" 1823 | ] 1824 | }, 1825 | { 1826 | "cell_type": "code", 1827 | "execution_count": 12, 1828 | "metadata": { 1829 | "collapsed": false 1830 | }, 1831 | "outputs": [ 1832 | { 1833 | "name": "stdout", 1834 | "output_type": "stream", 1835 | "text": [ 1836 | "----\n", 1837 | "----\n", 1838 | "1\n", 1839 | "----\n", 1840 | "----\n", 1841 | "3\n", 1842 | "----\n", 1843 | "----\n", 1844 | "5\n", 1845 | "----\n", 1846 | "----\n", 1847 | "7\n", 1848 | "----\n", 1849 | "----\n", 1850 | "9\n" 1851 | ] 1852 | } 1853 | ], 1854 | "source": [ 1855 | "for x in range(10):\n", 1856 | " print('----')\n", 1857 | " if x % 2 == 0:\n", 1858 | " continue\n", 1859 | " print(x)" 1860 | ] 1861 | }, 1862 | { 1863 | "cell_type": "code", 1864 | "execution_count": 14, 1865 | "metadata": { 1866 | "collapsed": false 1867 | }, 1868 | "outputs": [ 1869 | { 1870 | "name": "stdout", 1871 | "output_type": "stream", 1872 | "text": [ 1873 | "0\n", 1874 | "1\n" 1875 | ] 1876 | } 1877 | ], 1878 | "source": [ 1879 | "for x in range(10):\n", 1880 | " if x > 1:\n", 1881 | " break\n", 1882 | " print(x)\n", 1883 | "else:\n", 1884 | " print('###')" 1885 | ] 1886 | }, 1887 | { 1888 | "cell_type": "code", 1889 | "execution_count": 15, 1890 | "metadata": { 1891 | "collapsed": false 1892 | }, 1893 | "outputs": [ 1894 | { 1895 | "name": "stdout", 1896 | "output_type": "stream", 1897 | "text": [ 1898 | "ok\n" 1899 | ] 1900 | } 1901 | ], 1902 | "source": [ 1903 | "for x in range(0, 10, 2):\n", 1904 | " if x % 2 != 0:\n", 1905 | " break\n", 1906 | "else:\n", 1907 | " print('ok')" 1908 | ] 1909 | }, 1910 | { 1911 | "cell_type": "code", 1912 | "execution_count": null, 1913 | "metadata": { 1914 | "collapsed": true 1915 | }, 1916 | "outputs": [], 1917 | "source": [ 1918 | "is_ok = True\n", 1919 | "for x in range(0, 10, 2):\n", 1920 | " if x % 2 != 0:\n", 1921 | " is_ok = False\n", 1922 | " break\n", 1923 | "\n", 1924 | "if is_ok:\n", 1925 | " print('ok')" 1926 | ] 1927 | }, 1928 | { 1929 | "cell_type": "code", 1930 | "execution_count": null, 1931 | "metadata": { 1932 | "collapsed": true 1933 | }, 1934 | "outputs": [], 1935 | "source": [] 1936 | }, 1937 | { 1938 | "cell_type": "code", 1939 | "execution_count": null, 1940 | "metadata": { 1941 | "collapsed": true 1942 | }, 1943 | "outputs": [], 1944 | "source": [] 1945 | }, 1946 | { 1947 | "cell_type": "code", 1948 | "execution_count": null, 1949 | "metadata": { 1950 | "collapsed": true 1951 | }, 1952 | "outputs": [], 1953 | "source": [] 1954 | } 1955 | ], 1956 | "metadata": { 1957 | "kernelspec": { 1958 | "display_name": "Python 3", 1959 | "language": "python", 1960 | "name": "python3" 1961 | }, 1962 | "language_info": { 1963 | "codemirror_mode": { 1964 | "name": "ipython", 1965 | "version": 3 1966 | }, 1967 | "file_extension": ".py", 1968 | "mimetype": "text/x-python", 1969 | "name": "python", 1970 | "nbconvert_exporter": "python", 1971 | "pygments_lexer": "ipython3", 1972 | "version": "3.4.2" 1973 | } 1974 | }, 1975 | "nbformat": 4, 1976 | "nbformat_minor": 0 1977 | } 1978 | -------------------------------------------------------------------------------- /002/dict.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 字典" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "d = {}\n", 19 | "d = dict()\n", 20 | "d = {\"a\":1, \"b\":2}" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## 获取元素" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 2, 33 | "metadata": { 34 | "collapsed": false 35 | }, 36 | "outputs": [ 37 | { 38 | "data": { 39 | "text/plain": [ 40 | "1" 41 | ] 42 | }, 43 | "execution_count": 2, 44 | "metadata": {}, 45 | "output_type": "execute_result" 46 | } 47 | ], 48 | "source": [ 49 | "d['a']" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 3, 55 | "metadata": { 56 | "collapsed": false 57 | }, 58 | "outputs": [ 59 | { 60 | "data": { 61 | "text/plain": [ 62 | "1" 63 | ] 64 | }, 65 | "execution_count": 3, 66 | "metadata": {}, 67 | "output_type": "execute_result" 68 | } 69 | ], 70 | "source": [ 71 | "d.get('a')" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 4, 77 | "metadata": { 78 | "collapsed": false 79 | }, 80 | "outputs": [ 81 | { 82 | "ename": "KeyError", 83 | "evalue": "'c'", 84 | "output_type": "error", 85 | "traceback": [ 86 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 87 | "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", 88 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0md\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'c'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 89 | "\u001b[1;31mKeyError\u001b[0m: 'c'" 90 | ] 91 | } 92 | ], 93 | "source": [ 94 | "d['c']" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 5, 100 | "metadata": { 101 | "collapsed": true 102 | }, 103 | "outputs": [], 104 | "source": [ 105 | "d.get('c')" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": 6, 111 | "metadata": { 112 | "collapsed": false 113 | }, 114 | "outputs": [ 115 | { 116 | "name": "stdout", 117 | "output_type": "stream", 118 | "text": [ 119 | "Help on built-in function get:\n", 120 | "\n", 121 | "get(...) method of builtins.dict instance\n", 122 | " D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.\n", 123 | "\n" 124 | ] 125 | } 126 | ], 127 | "source": [ 128 | "help(d.get)" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 7, 134 | "metadata": { 135 | "collapsed": false 136 | }, 137 | "outputs": [ 138 | { 139 | "data": { 140 | "text/plain": [ 141 | "'abc'" 142 | ] 143 | }, 144 | "execution_count": 7, 145 | "metadata": {}, 146 | "output_type": "execute_result" 147 | } 148 | ], 149 | "source": [ 150 | "d.get('c', 'abc')" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "## 增加和修改元素" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": 8, 163 | "metadata": { 164 | "collapsed": true 165 | }, 166 | "outputs": [], 167 | "source": [ 168 | "d['a'] = 3" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": 9, 174 | "metadata": { 175 | "collapsed": false 176 | }, 177 | "outputs": [ 178 | { 179 | "data": { 180 | "text/plain": [ 181 | "{'a': 3, 'b': 2}" 182 | ] 183 | }, 184 | "execution_count": 9, 185 | "metadata": {}, 186 | "output_type": "execute_result" 187 | } 188 | ], 189 | "source": [ 190 | "d" 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": 10, 196 | "metadata": { 197 | "collapsed": true 198 | }, 199 | "outputs": [], 200 | "source": [ 201 | "d['c'] = 4" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": 11, 207 | "metadata": { 208 | "collapsed": false 209 | }, 210 | "outputs": [ 211 | { 212 | "data": { 213 | "text/plain": [ 214 | "{'a': 3, 'b': 2, 'c': 4}" 215 | ] 216 | }, 217 | "execution_count": 11, 218 | "metadata": {}, 219 | "output_type": "execute_result" 220 | } 221 | ], 222 | "source": [ 223 | "d" 224 | ] 225 | }, 226 | { 227 | "cell_type": "markdown", 228 | "metadata": {}, 229 | "source": [ 230 | "## 删除元素" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": 12, 236 | "metadata": { 237 | "collapsed": false 238 | }, 239 | "outputs": [ 240 | { 241 | "data": { 242 | "text/plain": [ 243 | "4" 244 | ] 245 | }, 246 | "execution_count": 12, 247 | "metadata": {}, 248 | "output_type": "execute_result" 249 | } 250 | ], 251 | "source": [ 252 | "d.pop('c')" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": 13, 258 | "metadata": { 259 | "collapsed": false 260 | }, 261 | "outputs": [ 262 | { 263 | "data": { 264 | "text/plain": [ 265 | "{'a': 3, 'b': 2}" 266 | ] 267 | }, 268 | "execution_count": 13, 269 | "metadata": {}, 270 | "output_type": "execute_result" 271 | } 272 | ], 273 | "source": [ 274 | "d" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "execution_count": 14, 280 | "metadata": { 281 | "collapsed": false 282 | }, 283 | "outputs": [ 284 | { 285 | "ename": "KeyError", 286 | "evalue": "'c'", 287 | "output_type": "error", 288 | "traceback": [ 289 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 290 | "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", 291 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0md\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'c'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 292 | "\u001b[1;31mKeyError\u001b[0m: 'c'" 293 | ] 294 | } 295 | ], 296 | "source": [ 297 | "d.pop('c')" 298 | ] 299 | }, 300 | { 301 | "cell_type": "code", 302 | "execution_count": 15, 303 | "metadata": { 304 | "collapsed": false 305 | }, 306 | "outputs": [ 307 | { 308 | "name": "stdout", 309 | "output_type": "stream", 310 | "text": [ 311 | "Help on built-in function pop:\n", 312 | "\n", 313 | "pop(...) method of builtins.dict instance\n", 314 | " D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n", 315 | " If key is not found, d is returned if given, otherwise KeyError is raised\n", 316 | "\n" 317 | ] 318 | } 319 | ], 320 | "source": [ 321 | "help(d.pop)" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": 16, 327 | "metadata": { 328 | "collapsed": false 329 | }, 330 | "outputs": [ 331 | { 332 | "data": { 333 | "text/plain": [ 334 | "'abc'" 335 | ] 336 | }, 337 | "execution_count": 16, 338 | "metadata": {}, 339 | "output_type": "execute_result" 340 | } 341 | ], 342 | "source": [ 343 | "d.pop('c', 'abc')" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": 17, 349 | "metadata": { 350 | "collapsed": false 351 | }, 352 | "outputs": [ 353 | { 354 | "data": { 355 | "text/plain": [ 356 | "('b', 2)" 357 | ] 358 | }, 359 | "execution_count": 17, 360 | "metadata": {}, 361 | "output_type": "execute_result" 362 | } 363 | ], 364 | "source": [ 365 | "d.popitem()" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": 18, 371 | "metadata": { 372 | "collapsed": true 373 | }, 374 | "outputs": [], 375 | "source": [ 376 | "del d['a']" 377 | ] 378 | }, 379 | { 380 | "cell_type": "markdown", 381 | "metadata": {}, 382 | "source": [ 383 | "## 遍历" 384 | ] 385 | }, 386 | { 387 | "cell_type": "code", 388 | "execution_count": 19, 389 | "metadata": { 390 | "collapsed": true 391 | }, 392 | "outputs": [], 393 | "source": [ 394 | "d = {'a': 1, 'b': 2, 'c': 3}" 395 | ] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "execution_count": 20, 400 | "metadata": { 401 | "collapsed": false 402 | }, 403 | "outputs": [ 404 | { 405 | "data": { 406 | "text/plain": [ 407 | "dict_keys(['b', 'c', 'a'])" 408 | ] 409 | }, 410 | "execution_count": 20, 411 | "metadata": {}, 412 | "output_type": "execute_result" 413 | } 414 | ], 415 | "source": [ 416 | "d.keys()" 417 | ] 418 | }, 419 | { 420 | "cell_type": "code", 421 | "execution_count": 21, 422 | "metadata": { 423 | "collapsed": false 424 | }, 425 | "outputs": [ 426 | { 427 | "name": "stdout", 428 | "output_type": "stream", 429 | "text": [ 430 | "b\n", 431 | "c\n", 432 | "a\n" 433 | ] 434 | } 435 | ], 436 | "source": [ 437 | "for k in d.keys():\n", 438 | " print(k)" 439 | ] 440 | }, 441 | { 442 | "cell_type": "code", 443 | "execution_count": 22, 444 | "metadata": { 445 | "collapsed": false 446 | }, 447 | "outputs": [ 448 | { 449 | "data": { 450 | "text/plain": [ 451 | "dict_values([2, 3, 1])" 452 | ] 453 | }, 454 | "execution_count": 22, 455 | "metadata": {}, 456 | "output_type": "execute_result" 457 | } 458 | ], 459 | "source": [ 460 | "d.values()" 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": 23, 466 | "metadata": { 467 | "collapsed": false 468 | }, 469 | "outputs": [ 470 | { 471 | "name": "stdout", 472 | "output_type": "stream", 473 | "text": [ 474 | "2\n", 475 | "3\n", 476 | "1\n" 477 | ] 478 | } 479 | ], 480 | "source": [ 481 | "for v in d.values():\n", 482 | " print(v)" 483 | ] 484 | }, 485 | { 486 | "cell_type": "code", 487 | "execution_count": 24, 488 | "metadata": { 489 | "collapsed": false 490 | }, 491 | "outputs": [ 492 | { 493 | "data": { 494 | "text/plain": [ 495 | "dict_items([('b', 2), ('c', 3), ('a', 1)])" 496 | ] 497 | }, 498 | "execution_count": 24, 499 | "metadata": {}, 500 | "output_type": "execute_result" 501 | } 502 | ], 503 | "source": [ 504 | "d.items()" 505 | ] 506 | }, 507 | { 508 | "cell_type": "code", 509 | "execution_count": 26, 510 | "metadata": { 511 | "collapsed": false 512 | }, 513 | "outputs": [ 514 | { 515 | "name": "stdout", 516 | "output_type": "stream", 517 | "text": [ 518 | "('b', 2)\n", 519 | "('c', 3)\n", 520 | "('a', 1)\n" 521 | ] 522 | } 523 | ], 524 | "source": [ 525 | "for t in d.items():\n", 526 | " print(t)" 527 | ] 528 | }, 529 | { 530 | "cell_type": "code", 531 | "execution_count": 27, 532 | "metadata": { 533 | "collapsed": false 534 | }, 535 | "outputs": [ 536 | { 537 | "name": "stdout", 538 | "output_type": "stream", 539 | "text": [ 540 | "b => 2\n", 541 | "c => 3\n", 542 | "a => 1\n" 543 | ] 544 | } 545 | ], 546 | "source": [ 547 | "for k, v in d.items():\n", 548 | " print('{0} => {1}'.format(k, v))" 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": 28, 554 | "metadata": { 555 | "collapsed": true 556 | }, 557 | "outputs": [], 558 | "source": [ 559 | "d = {}" 560 | ] 561 | }, 562 | { 563 | "cell_type": "code", 564 | "execution_count": 29, 565 | "metadata": { 566 | "collapsed": true 567 | }, 568 | "outputs": [], 569 | "source": [ 570 | "d['root'] = 'root'" 571 | ] 572 | }, 573 | { 574 | "cell_type": "code", 575 | "execution_count": 30, 576 | "metadata": { 577 | "collapsed": true 578 | }, 579 | "outputs": [], 580 | "source": [ 581 | "d['root'] = {}" 582 | ] 583 | }, 584 | { 585 | "cell_type": "code", 586 | "execution_count": 31, 587 | "metadata": { 588 | "collapsed": true 589 | }, 590 | "outputs": [], 591 | "source": [ 592 | "d['root']['left'] = 'left'\n", 593 | "d['root']['right'] = 'right'" 594 | ] 595 | }, 596 | { 597 | "cell_type": "code", 598 | "execution_count": 32, 599 | "metadata": { 600 | "collapsed": false 601 | }, 602 | "outputs": [ 603 | { 604 | "data": { 605 | "text/plain": [ 606 | "{'root': {'left': 'left', 'right': 'right'}}" 607 | ] 608 | }, 609 | "execution_count": 32, 610 | "metadata": {}, 611 | "output_type": "execute_result" 612 | } 613 | ], 614 | "source": [ 615 | "d" 616 | ] 617 | }, 618 | { 619 | "cell_type": "code", 620 | "execution_count": null, 621 | "metadata": { 622 | "collapsed": true 623 | }, 624 | "outputs": [], 625 | "source": [] 626 | }, 627 | { 628 | "cell_type": "code", 629 | "execution_count": null, 630 | "metadata": { 631 | "collapsed": true 632 | }, 633 | "outputs": [], 634 | "source": [] 635 | } 636 | ], 637 | "metadata": { 638 | "kernelspec": { 639 | "display_name": "Python 3", 640 | "language": "python", 641 | "name": "python3" 642 | }, 643 | "language_info": { 644 | "codemirror_mode": { 645 | "name": "ipython", 646 | "version": 3 647 | }, 648 | "file_extension": ".py", 649 | "mimetype": "text/x-python", 650 | "name": "python", 651 | "nbconvert_exporter": "python", 652 | "pygments_lexer": "ipython3", 653 | "version": "3.4.2" 654 | } 655 | }, 656 | "nbformat": 4, 657 | "nbformat_minor": 0 658 | } 659 | -------------------------------------------------------------------------------- /002/列表解析.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 列表解析" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "lst = list(range(10))" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "## 基本语法" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 2, 31 | "metadata": { 32 | "collapsed": false 33 | }, 34 | "outputs": [ 35 | { 36 | "data": { 37 | "text/plain": [ 38 | "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" 39 | ] 40 | }, 41 | "execution_count": 2, 42 | "metadata": {}, 43 | "output_type": "execute_result" 44 | } 45 | ], 46 | "source": [ 47 | "[x +1 for x in lst]" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 3, 53 | "metadata": { 54 | "collapsed": false 55 | }, 56 | "outputs": [ 57 | { 58 | "data": { 59 | "text/plain": [ 60 | "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" 61 | ] 62 | }, 63 | "execution_count": 3, 64 | "metadata": {}, 65 | "output_type": "execute_result" 66 | } 67 | ], 68 | "source": [ 69 | "l = []\n", 70 | "for x in lst:\n", 71 | " l.append(x+1)\n", 72 | "l" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": {}, 78 | "source": [ 79 | "## 带条件" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": 11, 85 | "metadata": { 86 | "collapsed": false 87 | }, 88 | "outputs": [ 89 | { 90 | "data": { 91 | "text/plain": [ 92 | "[1, 3, 5, 7, 9]" 93 | ] 94 | }, 95 | "execution_count": 11, 96 | "metadata": {}, 97 | "output_type": "execute_result" 98 | } 99 | ], 100 | "source": [ 101 | "[x+1 for x in lst if x % 2 == 0]" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": null, 107 | "metadata": { 108 | "collapsed": true 109 | }, 110 | "outputs": [], 111 | "source": [] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": 13, 116 | "metadata": { 117 | "collapsed": false 118 | }, 119 | "outputs": [ 120 | { 121 | "data": { 122 | "text/plain": [ 123 | "[1, 3, 5, 7, 9]" 124 | ] 125 | }, 126 | "execution_count": 13, 127 | "metadata": {}, 128 | "output_type": "execute_result" 129 | } 130 | ], 131 | "source": [ 132 | "l = []\n", 133 | "for x in lst:\n", 134 | " if x % 2 == 0:\n", 135 | " l.append(x+1)\n", 136 | "l" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 14, 142 | "metadata": { 143 | "collapsed": false 144 | }, 145 | "outputs": [ 146 | { 147 | "data": { 148 | "text/plain": [ 149 | "[5, 7, 9]" 150 | ] 151 | }, 152 | "execution_count": 14, 153 | "metadata": {}, 154 | "output_type": "execute_result" 155 | } 156 | ], 157 | "source": [ 158 | "[x + 1 for x in lst if x % 2 == 0 if x > 2]" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 17, 164 | "metadata": { 165 | "collapsed": false 166 | }, 167 | "outputs": [ 168 | { 169 | "data": { 170 | "text/plain": [ 171 | "[5, 7, 9]" 172 | ] 173 | }, 174 | "execution_count": 17, 175 | "metadata": {}, 176 | "output_type": "execute_result" 177 | } 178 | ], 179 | "source": [ 180 | "l = []\n", 181 | "for x in lst:\n", 182 | " if x % 2 == 0 \n", 183 | " if x > 2:\n", 184 | " l.append(x+1)\n", 185 | "l" 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "metadata": {}, 191 | "source": [ 192 | "## 多个列表" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": 18, 198 | "metadata": { 199 | "collapsed": true 200 | }, 201 | "outputs": [], 202 | "source": [ 203 | "l1 = [1, 3, 5, 7, 9]\n", 204 | "l2 = [0, 2, 4, 6, 8]" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": 19, 210 | "metadata": { 211 | "collapsed": false 212 | }, 213 | "outputs": [ 214 | { 215 | "data": { 216 | "text/plain": [ 217 | "[(1, 0),\n", 218 | " (1, 2),\n", 219 | " (1, 4),\n", 220 | " (1, 6),\n", 221 | " (1, 8),\n", 222 | " (3, 0),\n", 223 | " (3, 2),\n", 224 | " (3, 4),\n", 225 | " (3, 6),\n", 226 | " (3, 8),\n", 227 | " (5, 0),\n", 228 | " (5, 2),\n", 229 | " (5, 4),\n", 230 | " (5, 6),\n", 231 | " (5, 8),\n", 232 | " (7, 0),\n", 233 | " (7, 2),\n", 234 | " (7, 4),\n", 235 | " (7, 6),\n", 236 | " (7, 8),\n", 237 | " (9, 0),\n", 238 | " (9, 2),\n", 239 | " (9, 4),\n", 240 | " (9, 6),\n", 241 | " (9, 8)]" 242 | ] 243 | }, 244 | "execution_count": 19, 245 | "metadata": {}, 246 | "output_type": "execute_result" 247 | } 248 | ], 249 | "source": [ 250 | "[(x, y) for x in l1 for y in l2]" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": 20, 256 | "metadata": { 257 | "collapsed": false 258 | }, 259 | "outputs": [ 260 | { 261 | "data": { 262 | "text/plain": [ 263 | "[(1, 0),\n", 264 | " (1, 2),\n", 265 | " (1, 4),\n", 266 | " (1, 6),\n", 267 | " (1, 8),\n", 268 | " (3, 0),\n", 269 | " (3, 2),\n", 270 | " (3, 4),\n", 271 | " (3, 6),\n", 272 | " (3, 8),\n", 273 | " (5, 0),\n", 274 | " (5, 2),\n", 275 | " (5, 4),\n", 276 | " (5, 6),\n", 277 | " (5, 8),\n", 278 | " (7, 0),\n", 279 | " (7, 2),\n", 280 | " (7, 4),\n", 281 | " (7, 6),\n", 282 | " (7, 8),\n", 283 | " (9, 0),\n", 284 | " (9, 2),\n", 285 | " (9, 4),\n", 286 | " (9, 6),\n", 287 | " (9, 8)]" 288 | ] 289 | }, 290 | "execution_count": 20, 291 | "metadata": {}, 292 | "output_type": "execute_result" 293 | } 294 | ], 295 | "source": [ 296 | "l = []\n", 297 | "for x in l1:\n", 298 | " for y in l2:\n", 299 | " l.append((x, y))\n", 300 | "l" 301 | ] 302 | }, 303 | { 304 | "cell_type": "markdown", 305 | "metadata": {}, 306 | "source": [ 307 | "## 生成集合" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": null, 313 | "metadata": { 314 | "collapsed": true 315 | }, 316 | "outputs": [], 317 | "source": [] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": 21, 322 | "metadata": { 323 | "collapsed": true 324 | }, 325 | "outputs": [], 326 | "source": [ 327 | "s = {1, 3, 5}" 328 | ] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": 22, 333 | "metadata": { 334 | "collapsed": false 335 | }, 336 | "outputs": [ 337 | { 338 | "data": { 339 | "text/plain": [ 340 | "{2, 4, 6}" 341 | ] 342 | }, 343 | "execution_count": 22, 344 | "metadata": {}, 345 | "output_type": "execute_result" 346 | } 347 | ], 348 | "source": [ 349 | "{x +1 for x in s}" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": 23, 355 | "metadata": { 356 | "collapsed": false 357 | }, 358 | "outputs": [ 359 | { 360 | "data": { 361 | "text/plain": [ 362 | "[2, 4, 6]" 363 | ] 364 | }, 365 | "execution_count": 23, 366 | "metadata": {}, 367 | "output_type": "execute_result" 368 | } 369 | ], 370 | "source": [ 371 | "[x+1 for x in s]" 372 | ] 373 | }, 374 | { 375 | "cell_type": "code", 376 | "execution_count": 24, 377 | "metadata": { 378 | "collapsed": false 379 | }, 380 | "outputs": [ 381 | { 382 | "data": { 383 | "text/plain": [ 384 | "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}" 385 | ] 386 | }, 387 | "execution_count": 24, 388 | "metadata": {}, 389 | "output_type": "execute_result" 390 | } 391 | ], 392 | "source": [ 393 | "{x+1 for x in range(10)}" 394 | ] 395 | }, 396 | { 397 | "cell_type": "code", 398 | "execution_count": 25, 399 | "metadata": { 400 | "collapsed": false 401 | }, 402 | "outputs": [ 403 | { 404 | "data": { 405 | "text/plain": [ 406 | "{3}" 407 | ] 408 | }, 409 | "execution_count": 25, 410 | "metadata": {}, 411 | "output_type": "execute_result" 412 | } 413 | ], 414 | "source": [ 415 | "{x+1 for x in [2, 2, 2, 2]}" 416 | ] 417 | }, 418 | { 419 | "cell_type": "markdown", 420 | "metadata": {}, 421 | "source": [ 422 | "## 生成字典" 423 | ] 424 | }, 425 | { 426 | "cell_type": "code", 427 | "execution_count": 26, 428 | "metadata": { 429 | "collapsed": true 430 | }, 431 | "outputs": [], 432 | "source": [ 433 | "d = {'a':1, 'b': 2}" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": 28, 439 | "metadata": { 440 | "collapsed": false 441 | }, 442 | "outputs": [ 443 | { 444 | "data": { 445 | "text/plain": [ 446 | "{'a': 1, 'b': 2}" 447 | ] 448 | }, 449 | "execution_count": 28, 450 | "metadata": {}, 451 | "output_type": "execute_result" 452 | } 453 | ], 454 | "source": [ 455 | "{k:v for k, v in d.items()}" 456 | ] 457 | }, 458 | { 459 | "cell_type": "code", 460 | "execution_count": 29, 461 | "metadata": { 462 | "collapsed": false 463 | }, 464 | "outputs": [ 465 | { 466 | "data": { 467 | "text/plain": [ 468 | "{1: 8, 3: 8, 5: 8, 7: 8, 9: 8}" 469 | ] 470 | }, 471 | "execution_count": 29, 472 | "metadata": {}, 473 | "output_type": "execute_result" 474 | } 475 | ], 476 | "source": [ 477 | "{x: y for x in l1 for y in l2}" 478 | ] 479 | }, 480 | { 481 | "cell_type": "code", 482 | "execution_count": 31, 483 | "metadata": { 484 | "collapsed": false 485 | }, 486 | "outputs": [ 487 | { 488 | "data": { 489 | "text/plain": [ 490 | "{'a': 1, 'b': 2}" 491 | ] 492 | }, 493 | "execution_count": 31, 494 | "metadata": {}, 495 | "output_type": "execute_result" 496 | } 497 | ], 498 | "source": [ 499 | "{k:v for k, v in [('a', 1), ('b', 2)]}" 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": { 506 | "collapsed": true 507 | }, 508 | "outputs": [], 509 | "source": [] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "execution_count": null, 514 | "metadata": { 515 | "collapsed": true 516 | }, 517 | "outputs": [], 518 | "source": [] 519 | }, 520 | { 521 | "cell_type": "code", 522 | "execution_count": null, 523 | "metadata": { 524 | "collapsed": true 525 | }, 526 | "outputs": [], 527 | "source": [] 528 | }, 529 | { 530 | "cell_type": "code", 531 | "execution_count": null, 532 | "metadata": { 533 | "collapsed": true 534 | }, 535 | "outputs": [], 536 | "source": [] 537 | }, 538 | { 539 | "cell_type": "code", 540 | "execution_count": null, 541 | "metadata": { 542 | "collapsed": true 543 | }, 544 | "outputs": [], 545 | "source": [] 546 | }, 547 | { 548 | "cell_type": "code", 549 | "execution_count": null, 550 | "metadata": { 551 | "collapsed": true 552 | }, 553 | "outputs": [], 554 | "source": [] 555 | } 556 | ], 557 | "metadata": { 558 | "kernelspec": { 559 | "display_name": "Python 3", 560 | "language": "python", 561 | "name": "python3" 562 | }, 563 | "language_info": { 564 | "codemirror_mode": { 565 | "name": "ipython", 566 | "version": 3 567 | }, 568 | "file_extension": ".py", 569 | "mimetype": "text/x-python", 570 | "name": "python", 571 | "nbconvert_exporter": "python", 572 | "pygments_lexer": "ipython3", 573 | "version": "3.4.2" 574 | } 575 | }, 576 | "nbformat": 4, 577 | "nbformat_minor": 0 578 | } 579 | -------------------------------------------------------------------------------- /003/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "comyn" 3 | } 4 | -------------------------------------------------------------------------------- /005/OOP-2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## 继承" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "class Door:\n", 19 | " def __init__(self, number, status):\n", 20 | " self.number = number\n", 21 | " self.status = status\n", 22 | " \n", 23 | " def open(self):\n", 24 | " self.status = 'opening'\n", 25 | " \n", 26 | " def close(self):\n", 27 | " self.status = 'closed'" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 2, 33 | "metadata": { 34 | "collapsed": true 35 | }, 36 | "outputs": [], 37 | "source": [ 38 | "class LockableDoor:\n", 39 | " def __init__(self, number, status, is_locked):\n", 40 | " self.number = number\n", 41 | " self.status = status\n", 42 | " self.is_locked = is_locked\n", 43 | " \n", 44 | " def open(self):\n", 45 | " if not self.is_locked:\n", 46 | " self.status = 'opening'\n", 47 | " else:\n", 48 | " print('is locked')\n", 49 | " \n", 50 | " def close(self):\n", 51 | " self.staus = 'closed'\n", 52 | " \n", 53 | " def lock(self):\n", 54 | " if self.status == 'closed':\n", 55 | " self.is_locked = True\n", 56 | " else:\n", 57 | " print('is opening')" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 3, 63 | "metadata": { 64 | "collapsed": true 65 | }, 66 | "outputs": [], 67 | "source": [ 68 | "class LockableDoor(Door): # Door 是 LockableDoor 的 超类、父类、基类\n", 69 | " def __init__(self, number, status, is_locked):\n", 70 | " super(LockableDoor, self).__init__(number, status)\n", 71 | " self.is_locked = is_locked\n", 72 | " \n", 73 | " def open(self): # 重写\n", 74 | " if not self.is_locked:\n", 75 | " super(LockableDoor, self).open()\n", 76 | " else:\n", 77 | " print('is locked')\n", 78 | " \n", 79 | " def lock(self):\n", 80 | " if self.status == 'closed':\n", 81 | " self.is_locked = True\n", 82 | " else:\n", 83 | " print('is opening')" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": 4, 89 | "metadata": { 90 | "collapsed": false 91 | }, 92 | "outputs": [ 93 | { 94 | "name": "stdout", 95 | "output_type": "stream", 96 | "text": [ 97 | "Help on class super in module builtins:\n", 98 | "\n", 99 | "class super(object)\n", 100 | " | super() -> same as super(__class__, )\n", 101 | " | super(type) -> unbound super object\n", 102 | " | super(type, obj) -> bound super object; requires isinstance(obj, type)\n", 103 | " | super(type, type2) -> bound super object; requires issubclass(type2, type)\n", 104 | " | Typical use to call a cooperative superclass method:\n", 105 | " | class C(B):\n", 106 | " | def meth(self, arg):\n", 107 | " | super().meth(arg)\n", 108 | " | This works for class methods too:\n", 109 | " | class C(B):\n", 110 | " | @classmethod\n", 111 | " | def cmeth(cls, arg):\n", 112 | " | super().cmeth(arg)\n", 113 | " | \n", 114 | " | Methods defined here:\n", 115 | " | \n", 116 | " | __get__(self, instance, owner, /)\n", 117 | " | Return an attribute of instance, which is of type owner.\n", 118 | " | \n", 119 | " | __getattribute__(self, name, /)\n", 120 | " | Return getattr(self, name).\n", 121 | " | \n", 122 | " | __init__(self, /, *args, **kwargs)\n", 123 | " | Initialize self. See help(type(self)) for accurate signature.\n", 124 | " | \n", 125 | " | __new__(*args, **kwargs) from builtins.type\n", 126 | " | Create and return a new object. See help(type) for accurate signature.\n", 127 | " | \n", 128 | " | __repr__(self, /)\n", 129 | " | Return repr(self).\n", 130 | " | \n", 131 | " | ----------------------------------------------------------------------\n", 132 | " | Data descriptors defined here:\n", 133 | " | \n", 134 | " | __self__\n", 135 | " | the instance invoking super(); may be None\n", 136 | " | \n", 137 | " | __self_class__\n", 138 | " | the type of the instance invoking super(); may be None\n", 139 | " | \n", 140 | " | __thisclass__\n", 141 | " | the class invoking super()\n", 142 | "\n" 143 | ] 144 | } 145 | ], 146 | "source": [ 147 | "help(super)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "markdown", 152 | "metadata": {}, 153 | "source": [ 154 | "### 继承与可见性" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 12, 160 | "metadata": { 161 | "collapsed": true 162 | }, 163 | "outputs": [], 164 | "source": [ 165 | "class A:\n", 166 | " __class_private_var = 'class private var'\n", 167 | " class_public_var = 'class public var'\n", 168 | " \n", 169 | " def __init__(self):\n", 170 | " self.__instance_private_var = 'instance private var'\n", 171 | " self.instance_pubic_var = 'instance public var'\n", 172 | " \n", 173 | " def __intance_private_method(self):\n", 174 | " try:\n", 175 | " print(self.__class_private_var)\n", 176 | " except:\n", 177 | " pass\n", 178 | " try:\n", 179 | " print(self.class_public_var)\n", 180 | " except:\n", 181 | " pass\n", 182 | " try:\n", 183 | " print(self.__instance_private_var)\n", 184 | " except:\n", 185 | " pass\n", 186 | " try:\n", 187 | " print(self.instance_pubic_var)\n", 188 | " except:\n", 189 | " pass\n", 190 | " \n", 191 | " def instance_pubic_method(self):\n", 192 | " try:\n", 193 | " print(self.__class_private_var)\n", 194 | " except:\n", 195 | " pass\n", 196 | " try:\n", 197 | " print(self.class_public_var)\n", 198 | " except:\n", 199 | " pass\n", 200 | " try:\n", 201 | " print(self.__instance_private_var)\n", 202 | " except:\n", 203 | " pass\n", 204 | " try:\n", 205 | " print(self.instance_pubic_var)\n", 206 | " except:\n", 207 | " pass\n", 208 | " \n", 209 | " @classmethod\n", 210 | " def __private_class_method(cls):\n", 211 | " try:\n", 212 | " print(cls.__class_private_var)\n", 213 | " except:\n", 214 | " pass\n", 215 | " try:\n", 216 | " print(cls.class_public_var)\n", 217 | " except:\n", 218 | " pass\n", 219 | " \n", 220 | " @classmethod\n", 221 | " def public_class_method(cls):\n", 222 | " try:\n", 223 | " print(cls.__class_private_var)\n", 224 | " except:\n", 225 | " pass\n", 226 | " try:\n", 227 | " print(cls.class_public_var)\n", 228 | " except:\n", 229 | " pass\n", 230 | " " 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": 13, 236 | "metadata": { 237 | "collapsed": true 238 | }, 239 | "outputs": [], 240 | "source": [ 241 | "class B(A):\n", 242 | " pass" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 14, 248 | "metadata": { 249 | "collapsed": true 250 | }, 251 | "outputs": [], 252 | "source": [ 253 | "b = B()" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": 15, 259 | "metadata": { 260 | "collapsed": false 261 | }, 262 | "outputs": [ 263 | { 264 | "data": { 265 | "text/plain": [ 266 | "['_A__class_private_var',\n", 267 | " '_A__instance_private_var',\n", 268 | " '_A__intance_private_method',\n", 269 | " '_A__private_class_method',\n", 270 | " '__class__',\n", 271 | " '__delattr__',\n", 272 | " '__dict__',\n", 273 | " '__dir__',\n", 274 | " '__doc__',\n", 275 | " '__eq__',\n", 276 | " '__format__',\n", 277 | " '__ge__',\n", 278 | " '__getattribute__',\n", 279 | " '__gt__',\n", 280 | " '__hash__',\n", 281 | " '__init__',\n", 282 | " '__le__',\n", 283 | " '__lt__',\n", 284 | " '__module__',\n", 285 | " '__ne__',\n", 286 | " '__new__',\n", 287 | " '__reduce__',\n", 288 | " '__reduce_ex__',\n", 289 | " '__repr__',\n", 290 | " '__setattr__',\n", 291 | " '__sizeof__',\n", 292 | " '__str__',\n", 293 | " '__subclasshook__',\n", 294 | " '__weakref__',\n", 295 | " 'class_public_var',\n", 296 | " 'instance_pubic_method',\n", 297 | " 'instance_pubic_var',\n", 298 | " 'public_class_method']" 299 | ] 300 | }, 301 | "execution_count": 15, 302 | "metadata": {}, 303 | "output_type": "execute_result" 304 | } 305 | ], 306 | "source": [ 307 | "dir(b)" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": 16, 313 | "metadata": { 314 | "collapsed": false 315 | }, 316 | "outputs": [ 317 | { 318 | "ename": "AttributeError", 319 | "evalue": "'B' object has no attribute '__intance_private_method'", 320 | "output_type": "error", 321 | "traceback": [ 322 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 323 | "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", 324 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mb\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__intance_private_method\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 325 | "\u001b[1;31mAttributeError\u001b[0m: 'B' object has no attribute '__intance_private_method'" 326 | ] 327 | } 328 | ], 329 | "source": [ 330 | "b.__intance_private_method()" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": 17, 336 | "metadata": { 337 | "collapsed": false 338 | }, 339 | "outputs": [ 340 | { 341 | "ename": "AttributeError", 342 | "evalue": "'B' object has no attribute '__private_class_method'", 343 | "output_type": "error", 344 | "traceback": [ 345 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 346 | "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", 347 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mb\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__private_class_method\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 348 | "\u001b[1;31mAttributeError\u001b[0m: 'B' object has no attribute '__private_class_method'" 349 | ] 350 | } 351 | ], 352 | "source": [ 353 | "b.__private_class_method()" 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "execution_count": 18, 359 | "metadata": { 360 | "collapsed": false 361 | }, 362 | "outputs": [ 363 | { 364 | "name": "stdout", 365 | "output_type": "stream", 366 | "text": [ 367 | "class private var\n", 368 | "class public var\n", 369 | "instance private var\n", 370 | "instance public var\n" 371 | ] 372 | } 373 | ], 374 | "source": [ 375 | "b.instance_pubic_method()" 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": 19, 381 | "metadata": { 382 | "collapsed": false 383 | }, 384 | "outputs": [ 385 | { 386 | "name": "stdout", 387 | "output_type": "stream", 388 | "text": [ 389 | "class private var\n", 390 | "class public var\n" 391 | ] 392 | } 393 | ], 394 | "source": [ 395 | "b.public_class_method()" 396 | ] 397 | }, 398 | { 399 | "cell_type": "markdown", 400 | "metadata": {}, 401 | "source": [ 402 | "* 私有的方法、变量(类和实例)是不可继承的\n", 403 | "* 公有的方法、变量(类和实例)是可继承的\n", 404 | "* 父类公有的方法(类和实例)是可以访问父类的私有变量的" 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": 26, 410 | "metadata": { 411 | "collapsed": true 412 | }, 413 | "outputs": [], 414 | "source": [ 415 | "class B(A):\n", 416 | " __class_private_var = 'child class private var'\n", 417 | " class_public_var = 'child class public var'\n", 418 | " \n", 419 | " def __init__(self):\n", 420 | " super(B, self).__init__()\n", 421 | " self.__instance_private_var = 'child instance private var'\n", 422 | " self.instance_pubic_var = 'child instance public var'" 423 | ] 424 | }, 425 | { 426 | "cell_type": "code", 427 | "execution_count": 27, 428 | "metadata": { 429 | "collapsed": true 430 | }, 431 | "outputs": [], 432 | "source": [ 433 | "b = B()" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": 28, 439 | "metadata": { 440 | "collapsed": false 441 | }, 442 | "outputs": [ 443 | { 444 | "name": "stdout", 445 | "output_type": "stream", 446 | "text": [ 447 | "class private var\n", 448 | "child class public var\n", 449 | "instance private var\n", 450 | "child instance public var\n" 451 | ] 452 | } 453 | ], 454 | "source": [ 455 | "b.instance_pubic_method()" 456 | ] 457 | }, 458 | { 459 | "cell_type": "code", 460 | "execution_count": 29, 461 | "metadata": { 462 | "collapsed": false 463 | }, 464 | "outputs": [ 465 | { 466 | "data": { 467 | "text/plain": [ 468 | "['_A__class_private_var',\n", 469 | " '_A__instance_private_var',\n", 470 | " '_A__intance_private_method',\n", 471 | " '_A__private_class_method',\n", 472 | " '_B__class_private_var',\n", 473 | " '_B__instance_private_var',\n", 474 | " '__class__',\n", 475 | " '__delattr__',\n", 476 | " '__dict__',\n", 477 | " '__dir__',\n", 478 | " '__doc__',\n", 479 | " '__eq__',\n", 480 | " '__format__',\n", 481 | " '__ge__',\n", 482 | " '__getattribute__',\n", 483 | " '__gt__',\n", 484 | " '__hash__',\n", 485 | " '__init__',\n", 486 | " '__le__',\n", 487 | " '__lt__',\n", 488 | " '__module__',\n", 489 | " '__ne__',\n", 490 | " '__new__',\n", 491 | " '__reduce__',\n", 492 | " '__reduce_ex__',\n", 493 | " '__repr__',\n", 494 | " '__setattr__',\n", 495 | " '__sizeof__',\n", 496 | " '__str__',\n", 497 | " '__subclasshook__',\n", 498 | " '__weakref__',\n", 499 | " 'class_public_var',\n", 500 | " 'instance_pubic_method',\n", 501 | " 'instance_pubic_var',\n", 502 | " 'public_class_method']" 503 | ] 504 | }, 505 | "execution_count": 29, 506 | "metadata": {}, 507 | "output_type": "execute_result" 508 | } 509 | ], 510 | "source": [ 511 | "dir(b)" 512 | ] 513 | }, 514 | { 515 | "cell_type": "code", 516 | "execution_count": null, 517 | "metadata": { 518 | "collapsed": true 519 | }, 520 | "outputs": [], 521 | "source": [] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": 34, 526 | "metadata": { 527 | "collapsed": true 528 | }, 529 | "outputs": [], 530 | "source": [ 531 | "class A:\n", 532 | " def __method(self):\n", 533 | " print('method of A')" 534 | ] 535 | }, 536 | { 537 | "cell_type": "code", 538 | "execution_count": null, 539 | "metadata": { 540 | "collapsed": true 541 | }, 542 | "outputs": [], 543 | "source": [] 544 | }, 545 | { 546 | "cell_type": "code", 547 | "execution_count": 41, 548 | "metadata": { 549 | "collapsed": true 550 | }, 551 | "outputs": [], 552 | "source": [ 553 | "class B(A):\n", 554 | " def __method(self):\n", 555 | " super(B, self)._A__method()\n", 556 | " print('method of B')\n", 557 | " \n", 558 | " def method(self):\n", 559 | " self.__method()" 560 | ] 561 | }, 562 | { 563 | "cell_type": "code", 564 | "execution_count": 42, 565 | "metadata": { 566 | "collapsed": true 567 | }, 568 | "outputs": [], 569 | "source": [ 570 | "b = B()" 571 | ] 572 | }, 573 | { 574 | "cell_type": "code", 575 | "execution_count": 43, 576 | "metadata": { 577 | "collapsed": false 578 | }, 579 | "outputs": [ 580 | { 581 | "name": "stdout", 582 | "output_type": "stream", 583 | "text": [ 584 | "method of A\n", 585 | "method of B\n" 586 | ] 587 | } 588 | ], 589 | "source": [ 590 | "b.method()" 591 | ] 592 | }, 593 | { 594 | "cell_type": "markdown", 595 | "metadata": {}, 596 | "source": [ 597 | "## 多继承" 598 | ] 599 | }, 600 | { 601 | "cell_type": "code", 602 | "execution_count": 45, 603 | "metadata": { 604 | "collapsed": true 605 | }, 606 | "outputs": [], 607 | "source": [ 608 | "class A:\n", 609 | " def method_from_a(self):\n", 610 | " print('i am method of a')" 611 | ] 612 | }, 613 | { 614 | "cell_type": "code", 615 | "execution_count": 46, 616 | "metadata": { 617 | "collapsed": true 618 | }, 619 | "outputs": [], 620 | "source": [ 621 | "class B:\n", 622 | " def method_from_b(self):\n", 623 | " print('i am method of b')\n" 624 | ] 625 | }, 626 | { 627 | "cell_type": "code", 628 | "execution_count": 47, 629 | "metadata": { 630 | "collapsed": true 631 | }, 632 | "outputs": [], 633 | "source": [ 634 | "class C(A, B):\n", 635 | " pass" 636 | ] 637 | }, 638 | { 639 | "cell_type": "code", 640 | "execution_count": 48, 641 | "metadata": { 642 | "collapsed": true 643 | }, 644 | "outputs": [], 645 | "source": [ 646 | "c = C()" 647 | ] 648 | }, 649 | { 650 | "cell_type": "code", 651 | "execution_count": 49, 652 | "metadata": { 653 | "collapsed": false 654 | }, 655 | "outputs": [ 656 | { 657 | "name": "stdout", 658 | "output_type": "stream", 659 | "text": [ 660 | "i am method of a\n" 661 | ] 662 | } 663 | ], 664 | "source": [ 665 | "c.method_from_a()" 666 | ] 667 | }, 668 | { 669 | "cell_type": "code", 670 | "execution_count": 50, 671 | "metadata": { 672 | "collapsed": false 673 | }, 674 | "outputs": [ 675 | { 676 | "name": "stdout", 677 | "output_type": "stream", 678 | "text": [ 679 | "i am method of b\n" 680 | ] 681 | } 682 | ], 683 | "source": [ 684 | "c.method_from_b()" 685 | ] 686 | }, 687 | { 688 | "cell_type": "code", 689 | "execution_count": 51, 690 | "metadata": { 691 | "collapsed": true 692 | }, 693 | "outputs": [], 694 | "source": [ 695 | "class A:\n", 696 | " def method(self):\n", 697 | " print('method of A')\n" 698 | ] 699 | }, 700 | { 701 | "cell_type": "code", 702 | "execution_count": 55, 703 | "metadata": { 704 | "collapsed": true 705 | }, 706 | "outputs": [], 707 | "source": [ 708 | "class B:\n", 709 | " def method(self):\n", 710 | " print('method of B')" 711 | ] 712 | }, 713 | { 714 | "cell_type": "code", 715 | "execution_count": 56, 716 | "metadata": { 717 | "collapsed": true 718 | }, 719 | "outputs": [], 720 | "source": [ 721 | "class C(A, B):\n", 722 | " pass" 723 | ] 724 | }, 725 | { 726 | "cell_type": "code", 727 | "execution_count": 57, 728 | "metadata": { 729 | "collapsed": true 730 | }, 731 | "outputs": [], 732 | "source": [ 733 | "c = C()" 734 | ] 735 | }, 736 | { 737 | "cell_type": "code", 738 | "execution_count": 58, 739 | "metadata": { 740 | "collapsed": false 741 | }, 742 | "outputs": [ 743 | { 744 | "name": "stdout", 745 | "output_type": "stream", 746 | "text": [ 747 | "method of A\n" 748 | ] 749 | } 750 | ], 751 | "source": [ 752 | "c.method()" 753 | ] 754 | }, 755 | { 756 | "cell_type": "code", 757 | "execution_count": 59, 758 | "metadata": { 759 | "collapsed": true 760 | }, 761 | "outputs": [], 762 | "source": [ 763 | "class C(B, A):\n", 764 | " pass" 765 | ] 766 | }, 767 | { 768 | "cell_type": "code", 769 | "execution_count": 60, 770 | "metadata": { 771 | "collapsed": true 772 | }, 773 | "outputs": [], 774 | "source": [ 775 | "c = C()" 776 | ] 777 | }, 778 | { 779 | "cell_type": "code", 780 | "execution_count": 61, 781 | "metadata": { 782 | "collapsed": false 783 | }, 784 | "outputs": [ 785 | { 786 | "name": "stdout", 787 | "output_type": "stream", 788 | "text": [ 789 | "method of B\n" 790 | ] 791 | } 792 | ], 793 | "source": [ 794 | "c.method()" 795 | ] 796 | }, 797 | { 798 | "cell_type": "code", 799 | "execution_count": 62, 800 | "metadata": { 801 | "collapsed": true 802 | }, 803 | "outputs": [], 804 | "source": [ 805 | "class B(A):\n", 806 | " def method(self):\n", 807 | " print('method of B')" 808 | ] 809 | }, 810 | { 811 | "cell_type": "code", 812 | "execution_count": 63, 813 | "metadata": { 814 | "collapsed": false 815 | }, 816 | "outputs": [ 817 | { 818 | "ename": "TypeError", 819 | "evalue": "Cannot create a consistent method resolution\norder (MRO) for bases A, B", 820 | "output_type": "error", 821 | "traceback": [ 822 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 823 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 824 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mclass\u001b[0m \u001b[0mC\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mA\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mB\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[1;32mpass\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 825 | "\u001b[1;31mTypeError\u001b[0m: Cannot create a consistent method resolution\norder (MRO) for bases A, B" 826 | ] 827 | } 828 | ], 829 | "source": [ 830 | "class C(A, B):\n", 831 | " pass" 832 | ] 833 | }, 834 | { 835 | "cell_type": "code", 836 | "execution_count": 64, 837 | "metadata": { 838 | "collapsed": true 839 | }, 840 | "outputs": [], 841 | "source": [ 842 | "class C(B, A):\n", 843 | " pass" 844 | ] 845 | }, 846 | { 847 | "cell_type": "code", 848 | "execution_count": 65, 849 | "metadata": { 850 | "collapsed": true 851 | }, 852 | "outputs": [], 853 | "source": [ 854 | "c = C()" 855 | ] 856 | }, 857 | { 858 | "cell_type": "code", 859 | "execution_count": 66, 860 | "metadata": { 861 | "collapsed": false 862 | }, 863 | "outputs": [ 864 | { 865 | "name": "stdout", 866 | "output_type": "stream", 867 | "text": [ 868 | "method of B\n" 869 | ] 870 | } 871 | ], 872 | "source": [ 873 | "c.method()" 874 | ] 875 | }, 876 | { 877 | "cell_type": "markdown", 878 | "metadata": {}, 879 | "source": [ 880 | "### MRO method resolution order" 881 | ] 882 | }, 883 | { 884 | "cell_type": "markdown", 885 | "metadata": {}, 886 | "source": [ 887 | "MRO 通过 C3算法计算出来" 888 | ] 889 | }, 890 | { 891 | "cell_type": "markdown", 892 | "metadata": {}, 893 | "source": [ 894 | "class B: -> mro(B) = [B, O]\n", 895 | "\n", 896 | "class B(A1, A2, ...) -> mro(B) = [B] + merge(mro(A1), mro(A2), ..., [A1, A2, ...])" 897 | ] 898 | }, 899 | { 900 | "cell_type": "markdown", 901 | "metadata": {}, 902 | "source": [ 903 | "```\n", 904 | "C(A, B) - >\n", 905 | " [C] + merge(mro(A), mro(B), [A, B])\n", 906 | " [C] + merge([A, O], [B, O], [A, B])\n", 907 | " [C, A] + merge([O], [B, O], [B])\n", 908 | " [C, A, B] + merge([O], [O])\n", 909 | " [C, A, B, O]\n", 910 | "```" 911 | ] 912 | }, 913 | { 914 | "cell_type": "markdown", 915 | "metadata": {}, 916 | "source": [ 917 | "```\n", 918 | "C(B, A) ->\n", 919 | " [C] + merge(mro(B), mro(A), [B, A])\n", 920 | " [C] + merge([B, O], [A, O], [B, A])\n", 921 | " [C, B] + merge([O], [A, O], [A])\n", 922 | " [C, B, A] + merge([O], [O])\n", 923 | " [C, B, A, O]\n", 924 | "```" 925 | ] 926 | }, 927 | { 928 | "cell_type": "markdown", 929 | "metadata": {}, 930 | "source": [ 931 | "```\n", 932 | "C(A, B), B(A) ->\n", 933 | " [C] + merge(mro(A), mro(B), [A, B])\n", 934 | " [C] + merge([A, O], ([B] + merge(mro(A), [A]), [A, B])\n", 935 | " [C] + merge([A, O], ([B] + merge([A, O], [A])), [A, B])\n", 936 | " [C] + merge([A, O], ([B, A] + merge([O])), [A, B])\n", 937 | " [C] + merge([A, O], [B, A, O], [A, B])\n", 938 | " raise TypeError\n", 939 | " ```" 940 | ] 941 | }, 942 | { 943 | "cell_type": "markdown", 944 | "metadata": {}, 945 | "source": [ 946 | "```\n", 947 | "C(B, A), B(A) ->\n", 948 | " [C] + merge(mro(B), mro(A), [B, A])\n", 949 | " [C] + merge([B, A, O], [A, O], [B, A])\n", 950 | " [C, B] + merge([A, O], [A, O], [A])\n", 951 | " [C, B, A] + merge([O], [O])\n", 952 | " [C, B, A, O]\n", 953 | "\n", 954 | "```" 955 | ] 956 | }, 957 | { 958 | "cell_type": "markdown", 959 | "metadata": {}, 960 | "source": [ 961 | "```\n", 962 | "B(A) ->\n", 963 | " [B] + merge(mro(A), [A])\n", 964 | " [B] + merge([A, O], [A])\n", 965 | " [B, A] + merge([O])\n", 966 | " [B, A, O]\n", 967 | "\n", 968 | "C(A, B), B(A) ->\n", 969 | " [C] + merge(mro(A), mro(B), [A, B])\n", 970 | " [C] + merge([A, O], [B, A, O], [A, B])\n", 971 | " raise TypeError\n", 972 | "``` " 973 | ] 974 | }, 975 | { 976 | "cell_type": "code", 977 | "execution_count": 67, 978 | "metadata": { 979 | "collapsed": false 980 | }, 981 | "outputs": [ 982 | { 983 | "data": { 984 | "text/plain": [ 985 | "(__main__.C, __main__.B, __main__.A, object)" 986 | ] 987 | }, 988 | "execution_count": 67, 989 | "metadata": {}, 990 | "output_type": "execute_result" 991 | } 992 | ], 993 | "source": [ 994 | "C.__mro__" 995 | ] 996 | }, 997 | { 998 | "cell_type": "markdown", 999 | "metadata": {}, 1000 | "source": [ 1001 | "*Python 的多继承是一济毒药*" 1002 | ] 1003 | }, 1004 | { 1005 | "cell_type": "markdown", 1006 | "metadata": {}, 1007 | "source": [ 1008 | "### MIXIN" 1009 | ] 1010 | }, 1011 | { 1012 | "cell_type": "markdown", 1013 | "metadata": {}, 1014 | "source": [ 1015 | "他是实现组合的一种方式" 1016 | ] 1017 | }, 1018 | { 1019 | "cell_type": "code", 1020 | "execution_count": 97, 1021 | "metadata": { 1022 | "collapsed": true 1023 | }, 1024 | "outputs": [], 1025 | "source": [ 1026 | "class Document:\n", 1027 | " def __init__(self, content):\n", 1028 | " self.content = content\n", 1029 | " \n", 1030 | " def format(self):\n", 1031 | " pass\n", 1032 | " \n", 1033 | " def display(self):\n", 1034 | " raise NotImplementedError" 1035 | ] 1036 | }, 1037 | { 1038 | "cell_type": "code", 1039 | "execution_count": null, 1040 | "metadata": { 1041 | "collapsed": true 1042 | }, 1043 | "outputs": [], 1044 | "source": [] 1045 | }, 1046 | { 1047 | "cell_type": "code", 1048 | "execution_count": 98, 1049 | "metadata": { 1050 | "collapsed": true 1051 | }, 1052 | "outputs": [], 1053 | "source": [ 1054 | "class Word(Document):\n", 1055 | " def format(self):\n", 1056 | " self.content = 'i am word, my content is {0}'.format(self.content)" 1057 | ] 1058 | }, 1059 | { 1060 | "cell_type": "code", 1061 | "execution_count": null, 1062 | "metadata": { 1063 | "collapsed": true 1064 | }, 1065 | "outputs": [], 1066 | "source": [] 1067 | }, 1068 | { 1069 | "cell_type": "code", 1070 | "execution_count": 92, 1071 | "metadata": { 1072 | "collapsed": true 1073 | }, 1074 | "outputs": [], 1075 | "source": [ 1076 | "class Excel(Document):\n", 1077 | " def format(self):\n", 1078 | " self.content = 'i am excel, my content is {0}'.format(self.content)\n" 1079 | ] 1080 | }, 1081 | { 1082 | "cell_type": "code", 1083 | "execution_count": 73, 1084 | "metadata": { 1085 | "collapsed": true 1086 | }, 1087 | "outputs": [], 1088 | "source": [ 1089 | "class WordWithMonitor(Word):\n", 1090 | " def display(self):\n", 1091 | " print('{0} on monitor'.format(self.content))" 1092 | ] 1093 | }, 1094 | { 1095 | "cell_type": "code", 1096 | "execution_count": 74, 1097 | "metadata": { 1098 | "collapsed": true 1099 | }, 1100 | "outputs": [], 1101 | "source": [ 1102 | "class ExcelWithMonitor(Excel):\n", 1103 | " def display(self):\n", 1104 | " print('{0} on monitor'.format(self.content))" 1105 | ] 1106 | }, 1107 | { 1108 | "cell_type": "code", 1109 | "execution_count": 75, 1110 | "metadata": { 1111 | "collapsed": true 1112 | }, 1113 | "outputs": [], 1114 | "source": [ 1115 | "class WordWithHP(Word):\n", 1116 | " def display(self):\n", 1117 | " print('{0} on HP'.format(self.content))" 1118 | ] 1119 | }, 1120 | { 1121 | "cell_type": "code", 1122 | "execution_count": 76, 1123 | "metadata": { 1124 | "collapsed": true 1125 | }, 1126 | "outputs": [], 1127 | "source": [ 1128 | "class ExcelWithHP(Excel):\n", 1129 | " def display(self):\n", 1130 | " print('{0} on HP'.format(self.content))" 1131 | ] 1132 | }, 1133 | { 1134 | "cell_type": "code", 1135 | "execution_count": 77, 1136 | "metadata": { 1137 | "collapsed": true 1138 | }, 1139 | "outputs": [], 1140 | "source": [ 1141 | "class Monitor(object):\n", 1142 | " def display(self):\n", 1143 | " print('{0} on monitor'.format(self.content))" 1144 | ] 1145 | }, 1146 | { 1147 | "cell_type": "code", 1148 | "execution_count": 78, 1149 | "metadata": { 1150 | "collapsed": true 1151 | }, 1152 | "outputs": [], 1153 | "source": [ 1154 | "class HP:\n", 1155 | " def display(self):\n", 1156 | " print('{0} on HP'.format(self.content))" 1157 | ] 1158 | }, 1159 | { 1160 | "cell_type": "code", 1161 | "execution_count": 99, 1162 | "metadata": { 1163 | "collapsed": true 1164 | }, 1165 | "outputs": [], 1166 | "source": [ 1167 | "class WordWithMonitor(Monitor, Word):\n", 1168 | " pass" 1169 | ] 1170 | }, 1171 | { 1172 | "cell_type": "code", 1173 | "execution_count": null, 1174 | "metadata": { 1175 | "collapsed": true 1176 | }, 1177 | "outputs": [], 1178 | "source": [] 1179 | }, 1180 | { 1181 | "cell_type": "code", 1182 | "execution_count": null, 1183 | "metadata": { 1184 | "collapsed": true 1185 | }, 1186 | "outputs": [], 1187 | "source": [] 1188 | }, 1189 | { 1190 | "cell_type": "code", 1191 | "execution_count": 81, 1192 | "metadata": { 1193 | "collapsed": true 1194 | }, 1195 | "outputs": [], 1196 | "source": [ 1197 | "class ExcelWithMonitor(Excel, Monitor):\n", 1198 | " pass" 1199 | ] 1200 | }, 1201 | { 1202 | "cell_type": "code", 1203 | "execution_count": 100, 1204 | "metadata": { 1205 | "collapsed": true 1206 | }, 1207 | "outputs": [], 1208 | "source": [ 1209 | "wwm = WordWithMonitor('mix in')" 1210 | ] 1211 | }, 1212 | { 1213 | "cell_type": "code", 1214 | "execution_count": null, 1215 | "metadata": { 1216 | "collapsed": true 1217 | }, 1218 | "outputs": [], 1219 | "source": [] 1220 | }, 1221 | { 1222 | "cell_type": "code", 1223 | "execution_count": null, 1224 | "metadata": { 1225 | "collapsed": true 1226 | }, 1227 | "outputs": [], 1228 | "source": [] 1229 | }, 1230 | { 1231 | "cell_type": "code", 1232 | "execution_count": 101, 1233 | "metadata": { 1234 | "collapsed": true 1235 | }, 1236 | "outputs": [], 1237 | "source": [ 1238 | "wwm.format()" 1239 | ] 1240 | }, 1241 | { 1242 | "cell_type": "code", 1243 | "execution_count": null, 1244 | "metadata": { 1245 | "collapsed": true 1246 | }, 1247 | "outputs": [], 1248 | "source": [] 1249 | }, 1250 | { 1251 | "cell_type": "code", 1252 | "execution_count": null, 1253 | "metadata": { 1254 | "collapsed": true 1255 | }, 1256 | "outputs": [], 1257 | "source": [] 1258 | }, 1259 | { 1260 | "cell_type": "code", 1261 | "execution_count": 102, 1262 | "metadata": { 1263 | "collapsed": false 1264 | }, 1265 | "outputs": [ 1266 | { 1267 | "name": "stdout", 1268 | "output_type": "stream", 1269 | "text": [ 1270 | "i am word, my content is mix in on monitor\n" 1271 | ] 1272 | } 1273 | ], 1274 | "source": [ 1275 | "wwm.display()" 1276 | ] 1277 | }, 1278 | { 1279 | "cell_type": "code", 1280 | "execution_count": 103, 1281 | "metadata": { 1282 | "collapsed": false 1283 | }, 1284 | "outputs": [ 1285 | { 1286 | "data": { 1287 | "text/plain": [ 1288 | "(__main__.WordWithMonitor,\n", 1289 | " __main__.Monitor,\n", 1290 | " __main__.Word,\n", 1291 | " __main__.Document,\n", 1292 | " object)" 1293 | ] 1294 | }, 1295 | "execution_count": 103, 1296 | "metadata": {}, 1297 | "output_type": "execute_result" 1298 | } 1299 | ], 1300 | "source": [ 1301 | "WordWithMonitor.__mro__" 1302 | ] 1303 | }, 1304 | { 1305 | "cell_type": "code", 1306 | "execution_count": null, 1307 | "metadata": { 1308 | "collapsed": true 1309 | }, 1310 | "outputs": [], 1311 | "source": [] 1312 | }, 1313 | { 1314 | "cell_type": "code", 1315 | "execution_count": null, 1316 | "metadata": { 1317 | "collapsed": true 1318 | }, 1319 | "outputs": [], 1320 | "source": [] 1321 | }, 1322 | { 1323 | "cell_type": "code", 1324 | "execution_count": 85, 1325 | "metadata": { 1326 | "collapsed": false 1327 | }, 1328 | "outputs": [ 1329 | { 1330 | "data": { 1331 | "text/plain": [ 1332 | "['__class__',\n", 1333 | " '__delattr__',\n", 1334 | " '__dict__',\n", 1335 | " '__dir__',\n", 1336 | " '__doc__',\n", 1337 | " '__eq__',\n", 1338 | " '__format__',\n", 1339 | " '__ge__',\n", 1340 | " '__getattribute__',\n", 1341 | " '__gt__',\n", 1342 | " '__hash__',\n", 1343 | " '__init__',\n", 1344 | " '__le__',\n", 1345 | " '__lt__',\n", 1346 | " '__module__',\n", 1347 | " '__ne__',\n", 1348 | " '__new__',\n", 1349 | " '__reduce__',\n", 1350 | " '__reduce_ex__',\n", 1351 | " '__repr__',\n", 1352 | " '__setattr__',\n", 1353 | " '__sizeof__',\n", 1354 | " '__str__',\n", 1355 | " '__subclasshook__',\n", 1356 | " '__weakref__',\n", 1357 | " 'content',\n", 1358 | " 'display',\n", 1359 | " 'format']" 1360 | ] 1361 | }, 1362 | "execution_count": 85, 1363 | "metadata": {}, 1364 | "output_type": "execute_result" 1365 | } 1366 | ], 1367 | "source": [ 1368 | "dir(wwm)" 1369 | ] 1370 | }, 1371 | { 1372 | "cell_type": "code", 1373 | "execution_count": 86, 1374 | "metadata": { 1375 | "collapsed": false 1376 | }, 1377 | "outputs": [ 1378 | { 1379 | "data": { 1380 | "text/plain": [ 1381 | "'i am word, my content is mix in'" 1382 | ] 1383 | }, 1384 | "execution_count": 86, 1385 | "metadata": {}, 1386 | "output_type": "execute_result" 1387 | } 1388 | ], 1389 | "source": [ 1390 | "wwm.content" 1391 | ] 1392 | }, 1393 | { 1394 | "cell_type": "code", 1395 | "execution_count": 87, 1396 | "metadata": { 1397 | "collapsed": true 1398 | }, 1399 | "outputs": [], 1400 | "source": [ 1401 | "wwm.display()" 1402 | ] 1403 | }, 1404 | { 1405 | "cell_type": "code", 1406 | "execution_count": 88, 1407 | "metadata": { 1408 | "collapsed": false 1409 | }, 1410 | "outputs": [ 1411 | { 1412 | "ename": "AttributeError", 1413 | "evalue": "'WordWithMonitor' object has no attribute '__mro__'", 1414 | "output_type": "error", 1415 | "traceback": [ 1416 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 1417 | "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", 1418 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mwwm\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__mro__\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 1419 | "\u001b[1;31mAttributeError\u001b[0m: 'WordWithMonitor' object has no attribute '__mro__'" 1420 | ] 1421 | } 1422 | ], 1423 | "source": [ 1424 | "wwm.__mro__" 1425 | ] 1426 | }, 1427 | { 1428 | "cell_type": "code", 1429 | "execution_count": 89, 1430 | "metadata": { 1431 | "collapsed": false 1432 | }, 1433 | "outputs": [ 1434 | { 1435 | "data": { 1436 | "text/plain": [ 1437 | "(__main__.WordWithMonitor,\n", 1438 | " __main__.Word,\n", 1439 | " __main__.Document,\n", 1440 | " __main__.Monitor,\n", 1441 | " object)" 1442 | ] 1443 | }, 1444 | "execution_count": 89, 1445 | "metadata": {}, 1446 | "output_type": "execute_result" 1447 | } 1448 | ], 1449 | "source": [ 1450 | "WordWithMonitor.__mro__" 1451 | ] 1452 | }, 1453 | { 1454 | "cell_type": "code", 1455 | "execution_count": null, 1456 | "metadata": { 1457 | "collapsed": true 1458 | }, 1459 | "outputs": [], 1460 | "source": [] 1461 | }, 1462 | { 1463 | "cell_type": "code", 1464 | "execution_count": null, 1465 | "metadata": { 1466 | "collapsed": true 1467 | }, 1468 | "outputs": [], 1469 | "source": [] 1470 | }, 1471 | { 1472 | "cell_type": "code", 1473 | "execution_count": null, 1474 | "metadata": { 1475 | "collapsed": true 1476 | }, 1477 | "outputs": [], 1478 | "source": [] 1479 | } 1480 | ], 1481 | "metadata": { 1482 | "kernelspec": { 1483 | "display_name": "Python 3", 1484 | "language": "python", 1485 | "name": "python3" 1486 | }, 1487 | "language_info": { 1488 | "codemirror_mode": { 1489 | "name": "ipython", 1490 | "version": 3 1491 | }, 1492 | "file_extension": ".py", 1493 | "mimetype": "text/x-python", 1494 | "name": "python", 1495 | "nbconvert_exporter": "python", 1496 | "pygments_lexer": "ipython3", 1497 | "version": "3.4.2" 1498 | } 1499 | }, 1500 | "nbformat": 4, 1501 | "nbformat_minor": 0 1502 | } 1503 | -------------------------------------------------------------------------------- /006/exc.py: -------------------------------------------------------------------------------- 1 | def gen(): 2 | c = 0 3 | while True: 4 | yield 0 5 | c += 1 6 | if c > 3: 7 | raise GeneratorExit() 8 | 9 | for x in gen(): 10 | print(x) 11 | -------------------------------------------------------------------------------- /006/key.py: -------------------------------------------------------------------------------- 1 | try: 2 | while True: 3 | print('ha ha ha') 4 | except KeyboardInterrupt: 5 | print('exit...') 6 | -------------------------------------------------------------------------------- /006/异常处理.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# 异常处理" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": false 15 | }, 16 | "outputs": [ 17 | { 18 | "ename": "SyntaxError", 19 | "evalue": "invalid syntax (, line 1)", 20 | "output_type": "error", 21 | "traceback": [ 22 | "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m if True abc\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" 23 | ] 24 | } 25 | ], 26 | "source": [ 27 | "if True abc" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 2, 33 | "metadata": { 34 | "collapsed": false 35 | }, 36 | "outputs": [ 37 | { 38 | "ename": "ZeroDivisionError", 39 | "evalue": "division by zero", 40 | "output_type": "error", 41 | "traceback": [ 42 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 43 | "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", 44 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;36m3\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 45 | "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" 46 | ] 47 | } 48 | ], 49 | "source": [ 50 | "3/0" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": 4, 56 | "metadata": { 57 | "collapsed": false 58 | }, 59 | "outputs": [ 60 | { 61 | "name": "stdout", 62 | "output_type": "stream", 63 | "text": [ 64 | "start\n", 65 | "division by zero\n", 66 | "finally\n" 67 | ] 68 | } 69 | ], 70 | "source": [ 71 | "try:\n", 72 | " print('start')\n", 73 | " 3/0\n", 74 | " print('end')\n", 75 | "except ZeroDivisionError as e:\n", 76 | " print(e)\n", 77 | "finally:\n", 78 | " print('finally')" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 5, 84 | "metadata": { 85 | "collapsed": false 86 | }, 87 | "outputs": [ 88 | { 89 | "name": "stdout", 90 | "output_type": "stream", 91 | "text": [ 92 | "division by zero\n" 93 | ] 94 | } 95 | ], 96 | "source": [ 97 | "try:\n", 98 | " 3/0\n", 99 | "except SyntaxError as e:\n", 100 | " print(e)\n", 101 | "except ZeroDivisionError as e:\n", 102 | " print(e)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": 6, 108 | "metadata": { 109 | "collapsed": false 110 | }, 111 | "outputs": [ 112 | { 113 | "name": "stdout", 114 | "output_type": "stream", 115 | "text": [ 116 | "Exception\n" 117 | ] 118 | } 119 | ], 120 | "source": [ 121 | "try:\n", 122 | " 3/0\n", 123 | "except Exception:\n", 124 | " print('Exception')\n", 125 | "except ZeroDivisionError:\n", 126 | " print('ZeroDivisionError')" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 8, 132 | "metadata": { 133 | "collapsed": false 134 | }, 135 | "outputs": [ 136 | { 137 | "name": "stdout", 138 | "output_type": "stream", 139 | "text": [ 140 | "ha ha ha\n", 141 | "finally\n" 142 | ] 143 | } 144 | ], 145 | "source": [ 146 | "def p():\n", 147 | " print('ha ha ha')\n", 148 | "\n", 149 | " \n", 150 | "def main():\n", 151 | " try:\n", 152 | " return p()\n", 153 | " finally:\n", 154 | " print('finally')\n", 155 | "\n", 156 | "main()" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": { 163 | "collapsed": true 164 | }, 165 | "outputs": [], 166 | "source": [ 167 | "try:\n", 168 | " f = open('./Untitled.ipynb')\n", 169 | " 3/i\n", 170 | "except:\n", 171 | " print('eeeeee')\n", 172 | "finally:\n", 173 | " f.close()" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": { 180 | "collapsed": true 181 | }, 182 | "outputs": [], 183 | "source": [ 184 | "class InputLessZeroException(Exception):\n", 185 | " pass\n", 186 | "\n", 187 | "def fn(i):\n", 188 | " if i < 0:\n", 189 | " raise InputLessZeroException()\n", 190 | " \n", 191 | " " 192 | ] 193 | }, 194 | { 195 | "cell_type": "code", 196 | "execution_count": 10, 197 | "metadata": { 198 | "collapsed": false 199 | }, 200 | "outputs": [ 201 | { 202 | "name": "stdout", 203 | "output_type": "stream", 204 | "text": [ 205 | "division by zero\n" 206 | ] 207 | } 208 | ], 209 | "source": [ 210 | "def fn():\n", 211 | " 3/0\n", 212 | "\n", 213 | "def main():\n", 214 | " fn()\n", 215 | "\n", 216 | "try: \n", 217 | " main()\n", 218 | "except Exception as e:\n", 219 | " print(e)" 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": 11, 225 | "metadata": { 226 | "collapsed": true 227 | }, 228 | "outputs": [], 229 | "source": [ 230 | "class MyException(Exception):\n", 231 | " pass" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": 12, 237 | "metadata": { 238 | "collapsed": false 239 | }, 240 | "outputs": [ 241 | { 242 | "ename": "MyException", 243 | "evalue": "exception", 244 | "output_type": "error", 245 | "traceback": [ 246 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 247 | "\u001b[1;31mMyException\u001b[0m Traceback (most recent call last)", 248 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mMyException\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'exception'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 249 | "\u001b[1;31mMyException\u001b[0m: exception" 250 | ] 251 | } 252 | ], 253 | "source": [ 254 | "raise MyException('exception')" 255 | ] 256 | }, 257 | { 258 | "cell_type": "code", 259 | "execution_count": 13, 260 | "metadata": { 261 | "collapsed": false 262 | }, 263 | "outputs": [ 264 | { 265 | "name": "stdout", 266 | "output_type": "stream", 267 | "text": [ 268 | "abc\n" 269 | ] 270 | } 271 | ], 272 | "source": [ 273 | "try:\n", 274 | " raise MyException('abc')\n", 275 | "except MyException as e:\n", 276 | " print(e)" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": { 283 | "collapsed": true 284 | }, 285 | "outputs": [], 286 | "source": [] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": null, 291 | "metadata": { 292 | "collapsed": true 293 | }, 294 | "outputs": [], 295 | "source": [] 296 | } 297 | ], 298 | "metadata": { 299 | "kernelspec": { 300 | "display_name": "Python 3", 301 | "language": "python", 302 | "name": "python3" 303 | }, 304 | "language_info": { 305 | "codemirror_mode": { 306 | "name": "ipython", 307 | "version": 3 308 | }, 309 | "file_extension": ".py", 310 | "mimetype": "text/x-python", 311 | "name": "python", 312 | "nbconvert_exporter": "python", 313 | "pygments_lexer": "ipython3", 314 | "version": "3.4.2" 315 | } 316 | }, 317 | "nbformat": 4, 318 | "nbformat_minor": 0 319 | } 320 | -------------------------------------------------------------------------------- /007/bar.py: -------------------------------------------------------------------------------- 1 | from foo import fn as foo 2 | 3 | 4 | def fn(): 5 | foo() 6 | print('im bar') 7 | -------------------------------------------------------------------------------- /007/foo.py: -------------------------------------------------------------------------------- 1 | from bar import fn as bar 2 | 3 | 4 | def fn(): 5 | bar() 6 | print('im foo') 7 | -------------------------------------------------------------------------------- /007/m/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magedu/python2016/1b66b05987432d048b70db46fa1a7493b0a28b03/007/m/__init__.py -------------------------------------------------------------------------------- /007/m/bar.py: -------------------------------------------------------------------------------- 1 | from .foo import fn 2 | 3 | 4 | def bar(): 5 | fn() 6 | -------------------------------------------------------------------------------- /007/m/foo.py: -------------------------------------------------------------------------------- 1 | 2 | def fn(): 3 | print('i am in magedu.foo') 4 | -------------------------------------------------------------------------------- /007/m/sub/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magedu/python2016/1b66b05987432d048b70db46fa1a7493b0a28b03/007/m/sub/__init__.py -------------------------------------------------------------------------------- /007/m/sub/sub/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magedu/python2016/1b66b05987432d048b70db46fa1a7493b0a28b03/007/m/sub/sub/__init__.py -------------------------------------------------------------------------------- /007/m/sub/sub/y.py: -------------------------------------------------------------------------------- 1 | from ...foo import fn 2 | 3 | 4 | def y(): 5 | fn() -------------------------------------------------------------------------------- /007/m/sub/x.py: -------------------------------------------------------------------------------- 1 | from ..foo import fn 2 | 3 | def x(): 4 | fn() -------------------------------------------------------------------------------- /007/magedu_007.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /007/main.py: -------------------------------------------------------------------------------- 1 | from foo import fn 2 | 3 | fn() -------------------------------------------------------------------------------- /007/requirments.txt: -------------------------------------------------------------------------------- 1 | Jinja2==2.8 2 | MarkupSafe==0.23 3 | Pygments==2.1.3 4 | backports-abc==0.4 5 | decorator==4.0.9 6 | ipykernel==4.3.1 7 | ipython==4.1.2 8 | ipython-genutils==0.1.0 9 | ipywidgets==4.1.1 10 | jsonschema==2.5.1 11 | jupyter==1.0.0 12 | jupyter-client==4.2.0 13 | jupyter-console==4.1.1 14 | jupyter-core==4.0.6 15 | m==0.1.0 16 | mistune==0.7.2 17 | nbconvert==4.1.0 18 | nbformat==4.0.1 19 | notebook==4.1.0 20 | path.py==8.1.2 21 | pexpect==4.0.1 22 | pickleshare==0.6 23 | ptyprocess==0.5.1 24 | pyzmq==15.2.0 25 | qtconsole==4.2.0 26 | requests==2.9.0 27 | simplegeneric==0.8.1 28 | terminado==0.6 29 | tornado==4.3 30 | traitlets==4.1.0 31 | -------------------------------------------------------------------------------- /007/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='m', 5 | version='0.1.0', 6 | packages=find_packages(), 7 | install_requires=['requests>=2.9.0'] 8 | ) 9 | -------------------------------------------------------------------------------- /007/模块化.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import sys" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 2, 17 | "metadata": { 18 | "collapsed": false 19 | }, 20 | "outputs": [ 21 | { 22 | "data": { 23 | "text/plain": [ 24 | "'Copyright (c) 2001-2014 Python Software Foundation.\\nAll Rights Reserved.\\n\\nCopyright (c) 2000 BeOpen.com.\\nAll Rights Reserved.\\n\\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\\nAll Rights Reserved.\\n\\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\\nAll Rights Reserved.'" 25 | ] 26 | }, 27 | "execution_count": 2, 28 | "metadata": {}, 29 | "output_type": "execute_result" 30 | } 31 | ], 32 | "source": [ 33 | "sys.copyright" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 3, 39 | "metadata": { 40 | "collapsed": false 41 | }, 42 | "outputs": [ 43 | { 44 | "name": "stdout", 45 | "output_type": "stream", 46 | "text": [ 47 | "Copyright (c) 2001-2014 Python Software Foundation.\n", 48 | "All Rights Reserved.\n", 49 | "\n", 50 | "Copyright (c) 2000 BeOpen.com.\n", 51 | "All Rights Reserved.\n", 52 | "\n", 53 | "Copyright (c) 1995-2001 Corporation for National Research Initiatives.\n", 54 | "All Rights Reserved.\n", 55 | "\n", 56 | "Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\n", 57 | "All Rights Reserved.\n" 58 | ] 59 | } 60 | ], 61 | "source": [ 62 | "print(sys.copyright)" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 4, 68 | "metadata": { 69 | "collapsed": true 70 | }, 71 | "outputs": [], 72 | "source": [ 73 | "from os import path" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 5, 79 | "metadata": { 80 | "collapsed": false 81 | }, 82 | "outputs": [ 83 | { 84 | "data": { 85 | "text/plain": [ 86 | "'c'" 87 | ] 88 | }, 89 | "execution_count": 5, 90 | "metadata": {}, 91 | "output_type": "execute_result" 92 | } 93 | ], 94 | "source": [ 95 | "path.basename('/a/b/c')" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 6, 101 | "metadata": { 102 | "collapsed": true 103 | }, 104 | "outputs": [], 105 | "source": [ 106 | "import os" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": 7, 112 | "metadata": { 113 | "collapsed": false 114 | }, 115 | "outputs": [ 116 | { 117 | "data": { 118 | "text/plain": [ 119 | "'c'" 120 | ] 121 | }, 122 | "execution_count": 7, 123 | "metadata": {}, 124 | "output_type": "execute_result" 125 | } 126 | ], 127 | "source": [ 128 | "os.path.basename('/a/b/c')" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 8, 134 | "metadata": { 135 | "collapsed": true 136 | }, 137 | "outputs": [], 138 | "source": [ 139 | "from os.path import basename" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": 9, 145 | "metadata": { 146 | "collapsed": false 147 | }, 148 | "outputs": [ 149 | { 150 | "data": { 151 | "text/plain": [ 152 | "'c'" 153 | ] 154 | }, 155 | "execution_count": 9, 156 | "metadata": {}, 157 | "output_type": "execute_result" 158 | } 159 | ], 160 | "source": [ 161 | "basename('/a/b/c')" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": 10, 167 | "metadata": { 168 | "collapsed": true 169 | }, 170 | "outputs": [], 171 | "source": [ 172 | "import os.path" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": 11, 178 | "metadata": { 179 | "collapsed": true 180 | }, 181 | "outputs": [], 182 | "source": [ 183 | "import tornado.web" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": 12, 189 | "metadata": { 190 | "collapsed": true 191 | }, 192 | "outputs": [], 193 | "source": [ 194 | "class MainHandler(tornado.web.RequestHandler):\n", 195 | " pass" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": 13, 201 | "metadata": { 202 | "collapsed": true 203 | }, 204 | "outputs": [], 205 | "source": [ 206 | "from tornado.web import RequestHandler" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": 14, 212 | "metadata": { 213 | "collapsed": true 214 | }, 215 | "outputs": [], 216 | "source": [ 217 | "class MainHandler(RequestHandler):\n", 218 | " pass" 219 | ] 220 | }, 221 | { 222 | "cell_type": "code", 223 | "execution_count": 15, 224 | "metadata": { 225 | "collapsed": true 226 | }, 227 | "outputs": [], 228 | "source": [ 229 | "def basename():\n", 230 | " return 'ha ha ha'" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": 16, 236 | "metadata": { 237 | "collapsed": true 238 | }, 239 | "outputs": [], 240 | "source": [ 241 | "from os import path" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": 17, 247 | "metadata": { 248 | "collapsed": true 249 | }, 250 | "outputs": [], 251 | "source": [ 252 | "from os.path import basename as os_basename" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": 18, 258 | "metadata": { 259 | "collapsed": false 260 | }, 261 | "outputs": [ 262 | { 263 | "data": { 264 | "text/plain": [ 265 | "'c'" 266 | ] 267 | }, 268 | "execution_count": 18, 269 | "metadata": {}, 270 | "output_type": "execute_result" 271 | } 272 | ], 273 | "source": [ 274 | "os_basename('/a/b/c')" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "execution_count": 19, 280 | "metadata": { 281 | "collapsed": false 282 | }, 283 | "outputs": [ 284 | { 285 | "data": { 286 | "text/plain": [ 287 | "'ha ha ha'" 288 | ] 289 | }, 290 | "execution_count": 19, 291 | "metadata": {}, 292 | "output_type": "execute_result" 293 | } 294 | ], 295 | "source": [ 296 | "basename()" 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": 20, 302 | "metadata": { 303 | "collapsed": true 304 | }, 305 | "outputs": [], 306 | "source": [ 307 | "import sys as system" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": null, 313 | "metadata": { 314 | "collapsed": true 315 | }, 316 | "outputs": [], 317 | "source": [] 318 | } 319 | ], 320 | "metadata": { 321 | "kernelspec": { 322 | "display_name": "Python 3", 323 | "language": "python", 324 | "name": "python3" 325 | }, 326 | "language_info": { 327 | "codemirror_mode": { 328 | "name": "ipython", 329 | "version": 3 330 | }, 331 | "file_extension": ".py", 332 | "mimetype": "text/x-python", 333 | "name": "python", 334 | "nbconvert_exporter": "python", 335 | "pygments_lexer": "ipython3", 336 | "version": "3.4.2" 337 | } 338 | }, 339 | "nbformat": 4, 340 | "nbformat_minor": 0 341 | } 342 | -------------------------------------------------------------------------------- /008/expr.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from stack import Stack 4 | 5 | func_map = { 6 | '+': lambda x, y: x+y, 7 | '*': lambda x, y: x*y, 8 | '/': lambda x, y: x/y, 9 | '-': lambda x, y: x-y 10 | } 11 | 12 | # (3 + 4) * 5 / ((2+3) *3) 13 | def cacl(expr): 14 | stack = Stack() 15 | for c in expr: 16 | if c in '(+-*/': 17 | stack.push(c) 18 | elif c.strip() == '': 19 | pass 20 | else: 21 | if c != ')': 22 | c = int(c) 23 | if stack.top.value in '+-/*': 24 | s = stack.pop() 25 | if not isinstance(stack.top.value, (int, float)): 26 | raise Exception('wrong expr') 27 | v = stack.pop() 28 | v = func_map[s](v, c) 29 | stack.push(v) 30 | else: 31 | stack.push(c) 32 | if c == ')': 33 | if isinstance(stack.top.value, (int, float)): 34 | v = stack.pop() 35 | if stack.top.value == '(': 36 | stack.pop() 37 | stack.push(v) 38 | else: 39 | raise Exception('wrong expr') 40 | else: 41 | raise Exception('wrong expr') 42 | while stack.top: 43 | c = stack.pop() 44 | if not isinstance(c, (int, float)): 45 | raise Exception('wrong expr') 46 | if stack.top.value in '+-/*': 47 | s = stack.pop() 48 | if not isinstance(stack.top.value, (int, float)): 49 | raise Exception('wrong expr') 50 | v = stack.pop() 51 | v = func_map[s](v, c) 52 | if stack.top is None: 53 | return v 54 | stack.push(v) 55 | else: 56 | raise Exception('wrong expr') 57 | 58 | if __name__ == '__main__': 59 | print(cacl('(3 + 4) * 5 / ((2+3) *3)')) 60 | 61 | #TODO 实现带优先级的算术表达式解析 -------------------------------------------------------------------------------- /008/heap.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | 5 | class Heap: 6 | def __init__(self): 7 | self.__data = [] 8 | 9 | def insert(self, value): 10 | self.__data.append(value) 11 | idx = len(self.__data) - 1 12 | parent = math.floor((idx - 1) / 2) 13 | while parent >= 0 and self.__data[parent] < value: 14 | self.__data[idx] = self.__data[parent] 15 | self.__data[parent] = value 16 | idx = parent 17 | parent = math.floor((idx - 1) / 2) 18 | 19 | def pop(self): 20 | if not self.__data: 21 | raise Exception('Empty') 22 | ret = self.__data[0] 23 | value = self.__data.pop() 24 | self.__data[0] = value 25 | idx = 0 26 | left = 2 * idx + 1 27 | right = 2 * idx + 2 28 | while len(self.__data) > left: 29 | tmp_idx = left 30 | if len(self.__data) > right and self.__data[right] > self.__data[left]: 31 | tmp_idx = right 32 | if self.__data[tmp_idx] > value: 33 | self.__data[idx] = self.__data[tmp_idx] 34 | self.__data[tmp_idx] = value 35 | else: 36 | return ret 37 | idx = tmp_idx 38 | left = 2 * idx + 1 39 | right = 2 * idx + 2 40 | return ret 41 | 42 | def remove(self, i): 43 | if len(self.__data) - 1 < i: 44 | raise Exception('Empty') 45 | ret = self.__data[i] 46 | value = self.__data.pop() 47 | self.__data[i] = value 48 | idx = i 49 | left = 2 * idx + 1 50 | right = 2 * idx + 2 51 | while len(self.__data) > left: 52 | tmp_idx = left 53 | if len(self.__data) > right and self.__data[right] > self.__data[left]: 54 | tmp_idx = right 55 | if self.__data[tmp_idx] > value: 56 | self.__data[idx] = self.__data[tmp_idx] 57 | self.__data[tmp_idx] = value 58 | else: 59 | return ret 60 | idx = tmp_idx 61 | left = 2 * idx + 1 62 | right = 2 * idx + 2 63 | return ret 64 | 65 | def view(self): 66 | print(self.__data) 67 | 68 | if __name__ == '__main__': 69 | heap = Heap() 70 | for _ in range(8): 71 | i = random.randint(0, 100) 72 | print('i is ', i) 73 | heap.insert(i) 74 | heap.view() 75 | #heap.pop() 76 | heap.remove(1) 77 | heap.view() 78 | -------------------------------------------------------------------------------- /008/linklist.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.data = data 4 | self.next = None 5 | 6 | 7 | class LinkedList: 8 | def __init__(self): 9 | self.head = None 10 | self.tail = None 11 | 12 | def append(self, data): 13 | node = Node(data) 14 | if self.head is None: 15 | self.head = node 16 | self.tail = node 17 | else: 18 | self.tail.next = node 19 | self.tail = node 20 | 21 | def iter(self): 22 | if not self.head: 23 | return 24 | cur = self.head 25 | yield cur.data 26 | while cur.next: 27 | cur = cur.next 28 | yield cur.data 29 | 30 | def insert(self, idx, value): 31 | cur = self.head 32 | cur_idx = 0 33 | while cur_idx < idx-1: 34 | cur = cur.next 35 | if cur is None: 36 | raise Exception('list length less than index') 37 | cur_idx += 1 38 | node = Node(value) 39 | node.next = cur.next 40 | cur.next = node 41 | if node.next is None: 42 | self.tail = node 43 | 44 | def remove(self, idx): 45 | cur = self.head 46 | cur_idx = 0 47 | while cur_idx < idx-1: 48 | cur = cur.next 49 | if cur is None: 50 | raise Exception('list length less than index') 51 | cur_idx += 1 52 | cur.next = cur.next.next 53 | if cur.next is None: 54 | self.tail = cur 55 | 56 | if __name__ == '__main__': 57 | linked_list = LinkedList() 58 | for i in range(10): 59 | linked_list.append(i) 60 | 61 | linked_list.insert(3, 30) 62 | 63 | linked_list.remove(4) 64 | 65 | for node in linked_list.iter(): 66 | print(node) 67 | 68 | #TODO 判空 69 | #TODO 实现 __len__ -------------------------------------------------------------------------------- /008/map.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, key, value): 3 | self.key = key 4 | self.value = value 5 | 6 | def __eq__(self, other): 7 | return self.key == other.key 8 | 9 | 10 | class Map: 11 | def __init__(self, init_size, hash=hash): 12 | self.__slot = [[] for _ in range(init_size)] 13 | # for _ in range(init_size): 14 | # self.__slot.append([]) 15 | self.__size = init_size 16 | self.hash = hash 17 | 18 | def put(self, key, value): 19 | node = Node(key, value) 20 | address = self.hash(node.key) % self.__size 21 | self.__slot[address].append(node) 22 | 23 | def get(self, key, default=None): 24 | _key = self.hash(key) 25 | address = _key % self.__size 26 | for node in self.__slot[address]: 27 | if node.key == key: 28 | return node.value 29 | return default 30 | 31 | def remove(self, key): 32 | address = self.hash(key) % self.__size 33 | try: 34 | self.__slot[address].remove(Node(key, None)) 35 | except ValueError: 36 | pass 37 | # for idx, node in enumerate(self.__slot[address].copy()): 38 | # if node.key == key: 39 | # self.__slot[address].pop(idx) 40 | 41 | 42 | if __name__ == '__main__': 43 | map = Map(16) 44 | 45 | for i in range(20): 46 | map.put(i, i) 47 | 48 | map.remove(3) 49 | for i in range(20): 50 | print(map.get(i, 'not set')) -------------------------------------------------------------------------------- /008/rule_parser.py: -------------------------------------------------------------------------------- 1 | # #expr# & | ! () 2 | 3 | # (#e1# & #e2#) |(!#e3# & #e4#) 4 | 5 | from stack import Stack 6 | # '(#abc# & #324#) | (!#def# & #789#)' 7 | 8 | def match(exprs, line, fn): 9 | stack = Stack() 10 | is_expr = False 11 | expr = [] 12 | for c in exprs: 13 | if c == '#': 14 | if not is_expr: 15 | is_expr = True 16 | else: 17 | is_expr = False 18 | v = fn(line, ''.join(expr)) 19 | expr = [] 20 | if stack.top is None: 21 | stack.push(v) 22 | continue 23 | s = stack.pop() 24 | if s == '!': 25 | v = not v 26 | if stack.top is None: 27 | stack.push(v) 28 | continue 29 | s = stack.pop() 30 | if s == '&': 31 | if isinstance(stack.top.value, bool): 32 | v = stack.pop() and v 33 | stack.push(v) 34 | else: 35 | raise Exception('wrong expr') 36 | elif s == '|': 37 | if isinstance(stack.top.value, bool): 38 | v = stack.pop() or v 39 | stack.push(v) 40 | else: 41 | raise Exception('wrong expr') 42 | elif s == '(': 43 | stack.push(s) 44 | stack.push(v) 45 | else: 46 | raise Exception('wrong expr') 47 | else: 48 | if is_expr: 49 | expr.append(c) 50 | else: 51 | if c in '(&!|': 52 | stack.push(c) 53 | elif c.strip() == '': 54 | pass 55 | elif c == ')': 56 | v = stack.pop() 57 | if not isinstance(v, bool): 58 | raise Exception('wrong expr') 59 | s = stack.pop() 60 | if s == '!': 61 | v = not v 62 | s = stack.pop() 63 | if s == '(': 64 | stack.push(v) 65 | else: 66 | raise Exception('wrong expr') 67 | else: 68 | raise Exception('wrong expr') 69 | 70 | while stack.top: 71 | v = stack.pop() 72 | if not isinstance(v, bool): 73 | raise Exception('wrong expr') 74 | s = stack.pop() 75 | if s == '!': 76 | v = not v 77 | s = stack.pop() 78 | if s == '&': 79 | v2 = stack.pop() 80 | if not isinstance(v2, bool): 81 | raise Exception('wrong expr') 82 | v = v and v2 83 | elif s == '|': 84 | v2 = stack.pop() 85 | if not isinstance(v2, bool): 86 | raise Exception('wrong expr') 87 | v = v or v2 88 | else: 89 | raise Exception('wrong expr') 90 | if stack.top is None: 91 | return v 92 | else: 93 | stack.push(v) 94 | 95 | if __name__ == '__main__': 96 | import re 97 | line = 'abc 123 def 456 asd 789' 98 | exprs = '(#abc# & #324#) | (!#def# & #789#)' # False 99 | 100 | def callback(line, expr): 101 | return re.match(expr, line) is not None 102 | 103 | print(match(exprs, line, callback)) 104 | 105 | #TODO 优化两个程序, 使其模块化 -------------------------------------------------------------------------------- /008/stack.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, value): 3 | self.value = value 4 | self.next = None 5 | 6 | 7 | class Stack: 8 | def __init__(self): 9 | self.top = None 10 | 11 | def push(self, value): 12 | node = Node(value) 13 | node.next = self.top 14 | self.top = node 15 | 16 | def pop(self): 17 | node = self.top 18 | self.top = node.next 19 | return node.value 20 | 21 | 22 | if __name__ == '__main__': 23 | stack = Stack() 24 | exp = '({a * [x/(x+y)]}' 25 | for c in exp: 26 | if c in '{[(': 27 | stack.push(c) 28 | elif c in '}])': 29 | v = stack.top.value 30 | if c == '}' and v != '{': 31 | raise Exception('failed') 32 | if c == ']' and v != '[': 33 | raise Exception('failed') 34 | if c == ')' and v != '(': 35 | raise Exception('failed') 36 | stack.pop() 37 | if stack.top is not None: 38 | raise Exception('failed') 39 | print("ok") 40 | -------------------------------------------------------------------------------- /008/tree.py: -------------------------------------------------------------------------------- 1 | from stack import Stack 2 | from queue import Queue 3 | 4 | 5 | class Node: 6 | def __init__(self, value): 7 | self.value = value 8 | self.left = None 9 | self.right = None 10 | 11 | 12 | class Tree: 13 | def __init__(self, node): 14 | self.root = node 15 | 16 | def add_left(self, tree): 17 | self.root.left = tree 18 | 19 | def add_right(self, tree): 20 | self.root.right = tree 21 | 22 | @property 23 | def left(self): 24 | return self.root.left 25 | 26 | @property 27 | def right(self): 28 | return self.root.right 29 | 30 | def visit_first(self, fn): 31 | fn(self.root.value) 32 | if self.left: 33 | self.left.visit_first(fn) 34 | if self.right: 35 | self.right.visit_first(fn) 36 | 37 | def visit_middle(self, fn): 38 | if self.left: 39 | self.left.visit_middle(fn) 40 | fn(self.root.value) 41 | if self.right: 42 | self.right.visit_middle(fn) 43 | 44 | def visit_last(self, fn): 45 | if self.left: 46 | self.left.visit_last(fn) 47 | if self.right: 48 | self.right.visit_last(fn) 49 | fn(self.root.value) 50 | 51 | def iter_visit_first(self, fn): 52 | stack = Stack() 53 | stack.push(self) 54 | while stack.top: 55 | p = stack.pop() 56 | fn(p.root.value) 57 | if p.right: 58 | stack.push(p.right) 59 | if p.left: 60 | stack.push(p.left) 61 | 62 | def visit_level(self, fn): 63 | queue = Queue() 64 | queue.put(self) 65 | 66 | while not queue.empty(): 67 | p = queue.get() 68 | fn(p.root.value) 69 | if p.left: 70 | queue.put(p.left) 71 | if p.right: 72 | queue.put(p.right) 73 | 74 | 75 | if __name__ == '__main__': 76 | d = Tree(Node('D')) 77 | e = Tree(Node('E')) 78 | b = Tree(Node('B')) 79 | b.add_left(d) 80 | b.add_right(e) 81 | f = Tree(Node('F')) 82 | g = Tree(Node('G')) 83 | c = Tree(Node('C')) 84 | c.add_left(f) 85 | c.add_right(g) 86 | a = Tree(Node('A')) 87 | a.add_left(b) 88 | a.add_right(c) 89 | 90 | from functools import partial 91 | p = partial(print, end='') 92 | a.visit_first(p) 93 | print() 94 | a.iter_visit_first(p) 95 | print() 96 | a.visit_middle(p) 97 | print() 98 | a.visit_last(p) 99 | print() 100 | a.visit_level(p) 101 | 102 | #TODO 中序、后序便利的非第归方法 103 | 104 | # ABDECFG first 105 | # DBEAFCG middle 106 | # DEBFGCA last 107 | 108 | # ABCDEFG -------------------------------------------------------------------------------- /Python编程基础.xmind: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magedu/python2016/1b66b05987432d048b70db46fa1a7493b0a28b03/Python编程基础.xmind -------------------------------------------------------------------------------- /notes/.python-version: -------------------------------------------------------------------------------- 1 | system 2 | -------------------------------------------------------------------------------- /notes/20160221.adoc: -------------------------------------------------------------------------------- 1 | = 课堂回顾 2 | 2016-02-21 3 | 4 | == 环境准备 5 | 6 | === 安装pyenv 7 | 8 | * yum -y install git gcc make patch zlib-devel gdbm-devel openssl-devel sqlite-devel bzip2-devel readline-devel 9 | * curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash 10 | 11 | === pyenv 使用 12 | 13 | * pyenv install 3.4.2 14 | * pyenv virtualenv 3.4.2 magedu 15 | * pyenv local magedu 16 | 17 | === ipython 安装 18 | 19 | * pip install ipython 20 | * pip install jupyter 21 | * jupyter notebook 22 | 23 | 24 | == Python基础语法 25 | 26 | === 常量、变量、操作符、表达式 27 | 28 | * 字面常量 29 | * 变量 30 | * 数据类型 31 | * 操作符 特别注意出发操作 / 32 | * 操作符优先级 33 | * 表达式 特殊注意 逻辑操作的 *短路* 34 | 35 | === 程序控制结构 36 | 37 | ==== 顺序结构 38 | 39 | 默认结构 40 | 41 | ==== 分支结构 42 | 43 | * if 语句 44 | * if else 语句 45 | * if elif else 语句 46 | * 永远只有一个分支会被执行 47 | 48 | === 循环结构 49 | * while语句 50 | * for in 语句 51 | * for in的循环体里面永远不要修改迭代器 52 | * break语句 53 | * continue语句 54 | * else字句以及使用场景 55 | 56 | == 内置数据结构 57 | 58 | === 列表 59 | 60 | * 创建列表 [] list() 61 | * 列表的增删改查操作 62 | 63 | === 元组 64 | 65 | * 创建元组 () tupel() 66 | * 元组不可变 67 | * 仅有的两个操作 index count 68 | 69 | === 下标操作与切片 70 | 71 | * 通过下标访问元素 72 | * 切片 返回一个区间 [start:stop:step] 73 | * 切片的每个参数都可以是正整数,也可以是负整数 74 | * 切片每个参数的含义 75 | * 切片每个参数的默认值, start=0, stop=len(li) step=1 76 | 77 | === 集合 78 | 79 | * 创建集合 {1, 2, 3},set() 80 | * 集合的增删 81 | * 集合的集合操作 82 | 83 | === 字典 84 | 85 | * 创建字典 {} , dict() 86 | * 字典的遍历 keys, values, items 87 | * get 方法, 当key不存在的时候返回默认值, 默认的默认值是None 88 | * pop,popitem 方法, 从字典中删除元素 89 | 90 | -------------------------------------------------------------------------------- /notes/20160227-1.adoc: -------------------------------------------------------------------------------- 1 | == dict 2 | 3 | * 初始化 4 | * 获取元素, 下标操作和get 5 | * 修改元素 6 | * 删除元素 pop popitem del 7 | * 遍历 keys values items 8 | 9 | 10 | == 列表解析 11 | 12 | * 基本语法 [expr for item in iterator] 13 | * 带条件 14 | * 带多个条件的 相当and 15 | * 多个迭代器 相当于嵌套的循环 16 | * 集合解析 17 | * 字典解析 18 | 19 | 20 | == 字符串 21 | 22 | * 字符串是线性结构 切片 成员运算符 可以迭代 23 | * 字符串格式化 print style, format方法 24 | * 字符串的若干操作 join split strip replace startswith endswith 25 | * str 和bytes区别和相互转化 Python2 和Python3处理字符串的一些区别 26 | -------------------------------------------------------------------------------- /notes/20160227-2.adoc: -------------------------------------------------------------------------------- 1 | == 函数 2 | 3 | === 函数的基本语法 4 | 5 | * 定义函数 6 | * 调用函数 7 | 8 | === 函数的参数 9 | * 基本语法 10 | * 位置参数和关键字参数 11 | * 默认参数 12 | * 可变参数 13 | * 参数的规则 14 | * 默认的坑 15 | 16 | === 函数的返回值 17 | 18 | * 默认返回None 19 | * 通过unpacking变相的返回多值 其实返回的是一个元组tuple 20 | * 提前返回 21 | 22 | === 第归函数 23 | 24 | * 调用自己的函数 25 | * 一定要有退出条件 26 | * 第归最大深度1000 27 | * 尽量少用第归 28 | 29 | === 变量作用域和全局变量 30 | 31 | * 变量作用域 变量的可见范围 32 | * 全局变量 33 | * 局部作用域 赋值会生成新的局部变量, 除非global关键字 34 | * 尽量少用全局变量 35 | * globals() 和 locals() 36 | 37 | === 函数的执行流程 38 | 39 | === 生成器 40 | 41 | * 生成器的原理 42 | * 生成器的一些应用, 惰性求值, range xrange 43 | 44 | -------------------------------------------------------------------------------- /notes/20160228.adoc: -------------------------------------------------------------------------------- 1 | == 函数作为一等公民 first class 2 | 3 | === 高阶函数 接收函数作为参数 4 | 5 | === 函数作为返回值 6 | 7 | * 柯里化以及应用 8 | * functools.partial及其应用 9 | 10 | === 装饰器 11 | 12 | * 装饰器的原理 13 | * 带参数的装饰器 14 | * 现实世界中的装饰 -- 装饰器的作用 15 | * functools.wraps 的作用 16 | 17 | === 匿名函数 18 | -------------------------------------------------------------------------------- /notes/20160305-1.adoc: -------------------------------------------------------------------------------- 1 | = 面向对象 2 | 3 | == 哲学、方法学 4 | 5 | * 编程範式 6 | * OOP 7 | * OOP 的三大特征 封装 继承 多态 8 | * OOP 的本质 对数据和行为的封装 9 | 10 | == 类和对象 11 | 12 | * 定义类 13 | * 定义方法, self指什么 14 | * 构造方法 __init__ 15 | * __init__ 中的self是从那里来的, 以__init__ 方法作什么 16 | 17 | 18 | == 封装 19 | 20 | * 实例级 只有实例可以访问 21 | ** 实例变量 22 | ** 实例方法 23 | 24 | * 类级 类和实例都可以访问, 所有实例共享, 为什么对不变对象的重新复制,为什么其他实例不可见 25 | ** 类变量 26 | ** 类方法 27 | 28 | * 私有与共有 29 | ** 私有的只是类内部可以访问 30 | ** 共有的, 类外部也可以访问 31 | 32 | * 属性 property getter 和 setter 33 | 34 | 35 | -------------------------------------------------------------------------------- /notes/20160305-2.adoc: -------------------------------------------------------------------------------- 1 | == 继承 2 | 3 | * 继承一般语法 4 | * 默认继承自object 5 | * 父类对子类的可见性 父类的私有变量和私有方法 对子类是不可见 6 | * super 方法和 super对象 7 | 8 | == 多继承 9 | * 允许多继承 10 | * mro与C3算法 11 | * 尽量避免使用多继承 12 | * MixIn 用法,原则 13 | 14 | == 魔术方法/特殊方法 15 | 16 | * 总是以双下划线开始,双下划线结束 17 | * 实例的创建与销毁 18 | * 实例的可视化 repr str bytes 19 | * 比较运算符的重载 20 | -------------------------------------------------------------------------------- /notes/20160307.adoc: -------------------------------------------------------------------------------- 1 | == 魔术方法 2 | 3 | * bool 与 \\__bool__ \\__len__ 4 | * hash 与 \\__hash__ 5 | * 反射 \\__dict__ \\__dir__ \\__getattr__ \\__setattr__ dir getattr setattr 6 | * 描述器 \\__get__ \\__set__ \\__delete__ 7 | * 描述器 其实是一个方法传递 instance.property 等价于 Class.property.\\__get__(instance, Class) 8 | * instance.property = value 等价于 Class.property.\\__set__(instance, value) 9 | * del instance.property 等价于 Class.proppert.\\__delete__(instance) 10 | * @property @classmathod 11 | -------------------------------------------------------------------------------- /presentations/000_环境准备.adoc: -------------------------------------------------------------------------------- 1 | = 环境准备 2 | comyn 3 | v1.0 4 | :source-highlighter: pygments 5 | :revealjs_history: false 6 | :revealjs_center: false 7 | :revealjs_embedded: true 8 | :revealjsdir: ../reveal.js 9 | :imagesdir: assets/images/0 10 | :homepage: http://www.magedu.com 11 | 12 | == 操作系统 13 | 14 | [%step] 15 | * linux 16 | * osx 17 | 18 | == 操作系统 19 | 20 | [%step] 21 | * 推荐使用osx 22 | * 教学使用osx 23 | * 所有代码可以在linux上运行 24 | * 未经特殊说明的代码也可以在windows上运行 25 | 26 | == IDE & editor 27 | 28 | [%step] 29 | * PyCharm 30 | * Atom 31 | * vim 32 | * emacs 33 | 34 | == IDE & editor 35 | 36 | [%step] 37 | * 推荐使用PyCharm 38 | * 教学使用vim 39 | 40 | == Python版本 41 | 42 | [%step] 43 | * 教学使用3.4.2 44 | * 异步部分会介绍3.5的`async`和`await`关键字 45 | 46 | == 安装Python 47 | 48 | * 使用pyenv来管理Python环境 49 | 50 | === 安装pyenv 51 | 52 | [source,bash] 53 | ---- 54 | curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash 55 | ---- 56 | 57 | === pyenv基本使用 58 | 59 | * `pyenv install` 安装Python 60 | [source,bash] 61 | pyenv install 3.4.2 62 | 63 | * `pyenv virtualenv` 创建虚拟环境 64 | [source,bash] 65 | pyenv virtualenv 3.4.2 ch_0 66 | 67 | * `pyenv local` 设置使用Python版本 68 | [source,bash] 69 | pyenv local ch_0 70 | -------------------------------------------------------------------------------- /presentations/001_基础语法.adoc: -------------------------------------------------------------------------------- 1 | = 基础语法 2 | comyn 3 | v1.0 4 | :source-highlighter: pygments 5 | :revealjs_history: false 6 | :revealjs_center: false 7 | :revealjs_embedded: true 8 | :revealjsdir: ../reveal.js 9 | :imagesdir: assets/images/1 10 | :homepage: http://www.magedu.com 11 | 12 | == hello world 13 | [source,python] 14 | print('hello world') 15 | 16 | == 常量&变量 17 | 18 | === 字面常量 19 | 20 | [%step] 21 | * 单独出现的数字,字符串等 22 | * 字面常量是解释器里的一块内存 23 | * 单独出现的字面常量无意义 24 | 25 | === 变量 26 | 27 | [%step] 28 | * 解释器中一段内存的名称 29 | * Python中,变量都是引用 30 | 31 | === 数据类型 32 | 33 | [%step] 34 | * Python是强类型动态语言 35 | * 数据类型是对用来约束数据的。 36 | * 原始类型和复合类型 37 | 38 | == 运算符&表达式 39 | 40 | === 算术运算符 41 | _a = 10, b = 20_ 42 | [cols="2,2,5,4", options="header"] 43 | |=== 44 | |符号|名称|描述|实例 45 | |+|加|两个对象相加|a + b = 30 46 | |-|减|两个对象相减|a - b = -10 47 | |*|乘|两个对象相乘|a * b = 200 48 | |/|除|两个对象相除|a / b = 0.5 49 | |=== 50 | 51 | === 算术运算符 52 | _a = 10, b = 20_ 53 | [cols="2,2,5,4", options="header"] 54 | |=== 55 | |符号|名称|描述|实例 56 | |%|取模|返回除法的余数| a % b = 10 57 | |**|幂|返回x的y次幂|a ** b = 100000000000000000000 58 | |//|取整除|返回除法运算的整数部分|a // b = 0 59 | |=== 60 | 61 | === 位运算符 62 | _a=60(00111100) b=13(00001101)_ 63 | [cols="2,5,4"] 64 | |=== 65 | |符号|描述|实例 66 | |&|按位与|a & b = 12 67 | |\||按位或| a\|b = 61 68 | |^|按位异或|a^b = 49 69 | |~|按位取反| ~a = -61 70 | |=== 71 | 72 | === 位运算符 73 | _a=60(00111100) b=13(00001101)_ 74 | [cols="2,5,4"] 75 | |=== 76 | |符号|描述|实例 77 | |<<|左移| a << 2 = 240 78 | |>>|右移| a >> 2 = 15 79 | |=== 80 | 81 | === 比较运算符 82 | _a = 10, b = 20_ 83 | [cols="2,5,4", options="header"] 84 | |=== 85 | |符号|描述|实例 86 | |==|等于| a == b = False 87 | |!=|不等于| a != b = True 88 | |>|大于| a > b = False 89 | |<|小于|a < b = True 90 | |=== 91 | 92 | === 比较运算符 93 | _a = 10, b = 20_ 94 | [cols="2,5,4", options="header"] 95 | |=== 96 | |符号|描述|实例 97 | |>=|大于等于| a >= b = False 98 | |\<=|小于等于|a \<= b = True 99 | |=== 100 | 101 | === 逻辑运算符 102 | _a = True, b = False_ 103 | [cols="2,5,4", options="header"] 104 | |=== 105 | |符号|描述|实例 106 | |and|与| a and b = False 107 | |or|或|a or b = True 108 | |not|非| not a = False 109 | |=== 110 | 111 | === 其他运算符 112 | [cols="2,3,6", options="header"] 113 | |=== 114 | |符号|类别|描述 115 | |=|赋值运算符|a = b, 把b的值赋给a 116 | |in|成员运算符| a in b, a是否b的成员 117 | |not in| 成员运算符| a not in b, a是否不是b的成员 118 | |is|身份运算符| a is None, a是否None 119 | |is not|身份运算符| a is not None, a是否不是None 120 | |=== 121 | 122 | === 表达式 123 | * 常量、变量和赋值运算符之外的运算符的组合 124 | * 表达式可以求值 125 | 126 | === 表达式与优先级 127 | [%step] 128 | * 一元高于二元 129 | * 数值高于逻辑 130 | * 算术运算高于位运算 131 | * 乘除高于加减 132 | * 拿不准时加括号 133 | 134 | == 程序结构 135 | 对于大多数语言来说,有且仅有三种结构: 136 | 137 | * 顺序结构 138 | * 分支结构 139 | * 循环结构 140 | 141 | === 顺序结构 142 | * 顺序结构是绝大多数编程语言的默认结构 143 | * 指令按照书写顺序依次执行 144 | [source,python] 145 | ---- 146 | a = 10 147 | a += 2 148 | a << 2 149 | ---- 150 | a = 48 151 | 152 | === 分支结构 153 | 154 | === `if` 语句 155 | 当条件满足时,进入另外一个分支,执行一个块,执行完成重新回到主分支 156 | 157 | [source,python] 158 | ---- 159 | if condition: # <1> 160 | block # <2> 161 | ---- 162 | <1> Python 以 `:` 开始一个块 163 | <2> Python 使用缩进标示块 164 | 165 | === `else` 子句 166 | 在 `if` 语句的基础上,当条件不满足时,执行一个块,执行完成重新回到主分支 167 | [source,python] 168 | ---- 169 | if condition: 170 | block 171 | else: 172 | block 173 | ---- 174 | 175 | === `elif` 子句 176 | `elif` 是 `else` 和 `if` 的合体, 在 `if` 判断失效的情况下,做进一步判断 177 | [source,python] 178 | ---- 179 | if condition: 180 | block 181 | elif: 182 | block 183 | ---- 184 | 185 | === 关于 `switch` 186 | Python中并没有 `switch` 结构, 因为 `switch`结构完全可以由 `if elif else`语句来实现 187 | 188 | === 循环结构 189 | Python中有两种循环结构: 190 | 191 | * `while` 语句 192 | * `for` 语句 193 | 194 | === `while` 语句 195 | 循环执行,知道条件不满足,循环体内修改条件 196 | [source,python] 197 | ---- 198 | while condition: 199 | block 200 | ---- 201 | 202 | === `for` 语句 203 | 遍历某个可迭代对象的所有元素,循环体不应该修改迭代器 204 | [source,python] 205 | ---- 206 | for item in iterator: 207 | block 208 | ---- 209 | 210 | === `range` 函数 211 | `range` 函数产生一个生成器,通常用于控制循环次数 212 | 213 | * `range(x)` [0, x) 214 | * `range(m, n)` [m, n) 215 | * `range(m, n, s)` [m, n), 步长为 s 216 | 217 | === `break` 子句 218 | * 只能出现在循环结构中 219 | * 用于跳出当前循环结构 220 | 221 | === `continue` 子句 222 | * 只能出现在循环结构中 223 | * 用于跳过此次迭代的剩余操作 224 | 225 | === `else` 子句 226 | 循环结构的 `else` 子句是Python特有的,用于表示一个循环是 *未经`break`跳出* 的 227 | 228 | [source,python] 229 | ---- 230 | for item in iterator: 231 | block 232 | else: 233 | block 234 | ---- 235 | -------------------------------------------------------------------------------- /presentations/002_内置容器.adoc: -------------------------------------------------------------------------------- 1 | = 内置容器 2 | comyn 3 | v1.0 4 | :source-highlighter: pygments 5 | :revealjs_history: false 6 | :revealjs_center: false 7 | :revealjs_embedded: true 8 | :revealjsdir: ../reveal.js 9 | :imagesdir: assets/images/2 10 | :homepage: http://www.magedu.com 11 | 12 | == 列表 13 | * list是最常用的线性数据结构 14 | * list是一系列元素的有序组合 15 | * list是可变的 16 | 17 | === 列表的操作 18 | [%step] 19 | * 增:`append`, `extend`, `insert` 20 | * 删:`clear`, `pop`, `remove` 21 | * 改:`reverse`, `sort` 22 | * 查:`count`,`index` 23 | * 其他:`copy` 24 | 25 | == 元组 26 | * tuple和list大多数地方类似 27 | * tuple是不可变结构 28 | 29 | === 元组常用操作 30 | [%step] 31 | * 查:`count`,`index` 32 | 33 | == 下标操作与切片 34 | * 获取或修改当前值 `lst[x]` `lst[x] = n` 35 | * lst[b:e] 36 | * lst[b:e:s] 37 | 38 | == packing & unpacking 39 | [source,python] 40 | ---- 41 | x, y = (1, 2) # <1> 42 | t = x, y # <2> 43 | x, *y = (1, 2, 3, 4) # <3> 44 | *x, y = (1, 2, 3, 4) # <4> 45 | ---- 46 | <1> `x=1, y=2` 47 | <2> `t=(1, 2)` 48 | <3> `x=1, y=(2, 3, 4)` 49 | <4> `x=(1, 2, 3), y=4` 50 | 51 | == packing & unpacking 52 | [source,python] 53 | ---- 54 | x, *_, y = (1, 2, 3, 4) # <1> 55 | x, *_, y, z = (1, 2, 3, 4) #<2> 56 | x, (y, z) = (1, (2, 3)) # <3> 57 | ---- 58 | <1> `x=1, y=4` 59 | <2> `x=1, y=3, z=4` 60 | <3> `x=1, y=2, z=3` 61 | 62 | == 集合 63 | [%step] 64 | * 聚合的含义和数学上集合的含义相同 65 | * 集合不是线性结构 66 | * 集合元素是唯一的 67 | * 集合元素是可hash的 68 | 69 | === 集合的操作 70 | [%step] 71 | * 增:`add`, `update` 72 | * 删:`remove`, `discard`, `clear`, `pop` 73 | * 集合运算:`union`, `intersection`, `difference`, `symmetric_difference` 74 | * 集合判断:`issubset`, `issuperset`, `isdisjoint` 75 | 76 | == 字典 77 | [%step] 78 | * 字典是一种无序集合 79 | * 字典是一种KV结构 80 | * value可以是任何对象 81 | * key是唯一的 82 | * key必须是可hash对象 83 | 84 | === 字典的操作 85 | [%step] 86 | * 字典主要通过key来访问 87 | * `keys`, `values`, `items` 用于遍历字典 88 | * `pop`, `popitem` 用于删除元素 89 | 90 | == 列表解析 91 | * 列表解析是Python重要的语法糖 92 | * 列表解析的速度比 `for in` 迭代快 93 | 94 | === 基本语法 95 | [source,python] 96 | ---- 97 | ret = [expression for item in iterator] 98 | ---- 99 | 100 | 等价于 101 | 102 | [source,python] 103 | ---- 104 | ret = [] 105 | for item in iterator: 106 | ret.append(expression) 107 | ---- 108 | 109 | === 返回迭代器 110 | [source,python] 111 | ---- 112 | (expression for item in iterator) 113 | ---- 114 | 115 | 等价于 116 | 117 | [source,python] 118 | ---- 119 | for item in iterator: 120 | yield expression 121 | ---- 122 | 123 | === 字典解析 124 | [source,python] 125 | ---- 126 | ret = {exprK:exprV for item in iterator} 127 | ---- 128 | 129 | 等价于 130 | 131 | [source,python] 132 | ---- 133 | ret = dict() 134 | for item in iterator: 135 | ret.update({exprK: exprV}) 136 | ---- 137 | 138 | === 集合解析 139 | [source,python] 140 | ---- 141 | ret = {expression for item in iterator} 142 | ---- 143 | 144 | 等价于 145 | 146 | [source,python] 147 | ---- 148 | ret = set() 149 | for item in iterator: 150 | ret.add(expression) 151 | ---- 152 | 153 | === 带条件的列表解析 154 | [source,python] 155 | ---- 156 | ret = [expression for item in iterator if condition] 157 | ---- 158 | 159 | 等价于 160 | 161 | [source,python] 162 | ---- 163 | ret = [] 164 | for item in iterator: 165 | if condition: 166 | ret.append(expression) 167 | ---- 168 | 169 | === 带多个条件的列表解析 170 | [source,python] 171 | ---- 172 | ret = [expression for item in iterator if X if Y] 173 | ---- 174 | 175 | 等价于 176 | 177 | [source,python] 178 | ---- 179 | ret = [] 180 | for item in iterator: 181 | if X and Y: 182 | ret.append(expression) 183 | ---- 184 | 185 | === 笛卡尔积 186 | [source,python] 187 | ---- 188 | ret = [expression for x in X for y in Y] 189 | ---- 190 | 191 | 等价于 192 | 193 | [source,python] 194 | ---- 195 | ret = [] 196 | for x in X: 197 | for y in Y: 198 | ret.append(expression) 199 | ---- 200 | -------------------------------------------------------------------------------- /presentations/003_字符串与文本操作.adoc: -------------------------------------------------------------------------------- 1 | = 字符串与文本操作 2 | comyn 3 | v1.0 4 | :source-highlighter: pygments 5 | :revealjs_history: false 6 | :revealjs_center: false 7 | :revealjs_embedded: true 8 | :revealjsdir: ../reveal.js 9 | :imagesdir: assets/images/3 10 | :homepage: http://www.magedu.com 11 | 12 | == 字符串 13 | * Python 2和Python 3最大的差别就在于字符串 14 | * Python 2中字符串是byte的有序序列 15 | * Python 3中字符串是unicode的有序序列 16 | * 字符串是不可变的 17 | * 字符串支持下标与切片 18 | 19 | == 字符串格式化 20 | [%step] 21 | * Python字符串支持两种方式格式化 22 | * print style format 23 | * format方法 24 | 25 | === print style format 26 | [source,python] 27 | ---- 28 | template % tuple # <1> 29 | template % dict # <2> 30 | ---- 31 | <1> `template` 为带有一些标记的字符串,使用 `tuple` 中的元素一次填充 32 | <2> `template` 为带有一些标记的字符串,使用 `dict` 中的values按key填充 33 | 34 | === template 的一般格式 35 | [source,python] 36 | ---- 37 | % (key) flag conversion # <1> <2> <3> <4> 38 | ---- 39 | <1> `%` 开始 40 | <2> 可选的 `(key)` 如果指定了key, 将从字典中获取对应的value, 否则根据位置从元组中获取 41 | <3> 可选的 flag 42 | <4> 必选的 conversion 43 | 44 | === flag 45 | [cols="1,4,4", options="header"] 46 | |=== 47 | |Flag|说明|实例 48 | |#|此处 `#` 代表一个数字,指定宽度,如果宽度不够,会更具以下的规则填充|`'%3s' % ('a', )` -> '••a' 49 | |0|使用0填充,仅适用于数字|`'%03d' % (1,)` -> '001' 50 | |•|使用空格填充,默认行为|`'%•3d' % (1,) ` -> '••1' 51 | |=== 52 | 53 | === flag 54 | [cols="1,4,4", options="header"] 55 | |=== 56 | |Flag|说明|实例 57 | |-|右边使用空格填充|`'%-3d' % (1,)` -> '1••' 58 | |+|填充之前增加`+` 仅对于正数|`'%+03d' % (1, )` -> '+01' 59 | |=== 60 | 61 | === Conversion 62 | [cols="1,5,1,5", options="header"] 63 | |=== 64 | |符号|说明|符号|说明 65 | |d|整数|i|整数 66 | |o|八进制整数|u|整数,已废弃 67 | |x|小写十六进制整数|X|大写十六进制整数 68 | |f|浮点数|F|浮点数 69 | |e|小写科学计数法|E|大写科学计数法 70 | |=== 71 | 72 | === Conversion 73 | [cols="1,5,1,5", options="header"] 74 | |=== 75 | |符号|说明|符号|说明 76 | |g|同f, 如果指数小于-4,同e|G|同f, 如果指数小于-4,同E 77 | |c|字符,接收unicode编码或单字符字符串|a|字符串,使用 `ascii` 函数转换 78 | |r|字符串,使用 `repr` 函数转换|s|字符串,使用 `str` 函数转换 79 | |=== 80 | 81 | === format函数 82 | [source,python] 83 | ---- 84 | template.format(*args, **kwargs) # <1> <2> <3> <4> 85 | ---- 86 | <1> `template` 使用 `{}` 标示变量 87 | <2> `{}` 或 `{\d+}` 使用 `*args` 按顺序填充 88 | <3> `{key}` 使用 `**kwargs` 按key填充 89 | <4> https://docs.python.org/3/library/string.html#formatstrings[Format String Syntax] 90 | 91 | 92 | == 字符串常用操作 93 | * 字符串连接 `join` 94 | * 字符串分割 `split`, `rsplit`, `splitlines`, `partition`, `rpartition` 95 | * 字符串修改-大小写 `capitalize`, `title`, `lower`, `upper`, `swapcase` 96 | * 字符串修改-填充清除 `center`, `ljust`, `rjust`, `zfill`, `strip`, `rstrip`, `lstrip` 97 | * 字符串判断 `startswith`, `endswith`, `is{asterisk}` 98 | * 字符串查找替换 `count`, `find`, `rfind`, `index`, `rindex`,`replace` 99 | 100 | == str与bytes 101 | [%step] 102 | * Python3中严格区分了文本和二进制数据 103 | * Python2并没有严格区分 104 | * 文本数据使用str类型,底层实现是unicode 105 | * 二进制数据使用bytes类型,底层是byte 106 | * str使用encode方法转化为bytes 107 | * bytes方法使用decode方法转化为str 108 | * 由于清晰的区分文本和二进制,Python3解决了大多数Python2的编码问题 109 | -------------------------------------------------------------------------------- /presentations/004_函数.adoc: -------------------------------------------------------------------------------- 1 | = 函数 2 | comyn 3 | v1.0 4 | :source-highlighter: pygments 5 | :revealjs_history: false 6 | :revealjs_center: false 7 | :revealjs_embedded: true 8 | :revealjsdir: ../reveal.js 9 | :imagesdir: assets/images/3 10 | :homepage: http://www.magedu.com 11 | 12 | == 什么是函数 13 | * 函数是组织好的、可重复使用的、实现单一功能的代码段 14 | * 函数有输入(参数)和输出(返回值) 15 | * Python中,函数是一等对象(first class) 16 | 17 | == 函数的定义 18 | 19 | === 最简单的函数定义 20 | [source,python] 21 | ---- 22 | def fn(): 23 | block 24 | ---- 25 | 26 | ==== 调用方法 27 | [source,python] 28 | ---- 29 | fn() 30 | ---- 31 | 32 | === 带参数的函数定义 33 | [source,python] 34 | ---- 35 | def fn(parameters): # <1> 36 | block 37 | ---- 38 | <1> 多个参数使用逗号分隔 39 | 40 | ==== 调用方法 41 | [source,python] 42 | ---- 43 | fn(parameters) 44 | ---- 45 | 46 | === 位置参数和关键字参数 47 | [source,python] 48 | ---- 49 | def fn(a, b): # <1> 50 | pass 51 | 52 | fn(1, 2) # <2> 53 | 54 | fn(a=1, b=2) # <3> 55 | 56 | fn(1, b=2) #<4> 57 | ---- 58 | <1> 函数定义 59 | <2> 位置参数 60 | <3> 关键字参数 61 | <4> 混合使用, 注意:位置参数永远在关键字参数之前 62 | 63 | === 默认参数 64 | [source,python] 65 | ---- 66 | def fn(a, b=2): # <1> <4> 67 | pass 68 | 69 | fn(1, 3) # <2> 70 | 71 | fn(1) # <3> 72 | ---- 73 | <1> 函数定义时,可以为参数指定一个默认值 74 | <2> 函数调用时,可以覆盖默认值,`b=3` 75 | <3> 也可以省略这个参数,使用默认值, `b=2` 76 | <4> 函数定义时,带有默认值的参数应该在无默认值参数之后 77 | 78 | === 可变参数 -- 可变位置参数 79 | [source,python] 80 | ---- 81 | def fn(*args): #<1> 82 | pass 83 | 84 | fn(1, 2, 3) #<2> 85 | ---- 86 | <1> 函数定义时, 参数名之前加 `*` 代表此参数是可变的位置参数 87 | <2> 函数调用时,参数列表封装成一个元组传递给 `args` 88 | 89 | === 思考 90 | [source,python] 91 | ---- 92 | def f1(a, b=1, *args): 93 | pass 94 | 95 | def f2(a, *args, b=1): 96 | pass 97 | 98 | def f3(*args, a, b=1): 99 | pass 100 | ---- 101 | 以上函数应该怎么调用,a, b, args的值各是什么? 102 | 103 | === 可变参数 -- 可变关键字参数 104 | [source,python] 105 | ---- 106 | def fn(**kwargs): #<1> <3> 107 | pass 108 | 109 | fn(a=1, b=2) # <2> 110 | ---- 111 | <1> 函数定义时,使用 `**` 表示此参数是可变的位置参数 112 | <2> 函数调用时,关键字参数封装成字典,传递给 `kwargs` 113 | <3> 可变关键字参数应该在参数列表的最后 114 | 115 | === 参数解包 116 | [source,python] 117 | ---- 118 | a = [1, 2, 3] 119 | b = {'a': 1, 'b': 2, 'c': 3} 120 | 121 | def fn(a, b, c): 122 | pass 123 | 124 | fn(*a) # <1> 125 | fn(**b) # <2> 126 | fn(*[1, 2], **{'c': 3}) # <3> 127 | ---- 128 | <1> 可以用 `*` 解包列表或者元组作为位置参数 129 | <2> 可以用 `**` 解包字典为关键字参数 130 | <3> 也可以混合使用,思考:`fn(*[1, 2], **{'c': 3, 'a': 4})` 会怎么样? 131 | 132 | == 函数返回值 133 | [%step] 134 | * 使用 `return` 关键字返回 135 | * 可以返回任何对象 136 | * 可以通过解包变相返回多值 137 | * 默认返回 `None` 138 | 139 | == 递归函数 140 | [%step] 141 | * 函数体内调用自身的函数 142 | * 递归函数需要有合适的退出条件 143 | * 迭代都可以转化为递归 144 | * 递归不一定可以转化为迭代 145 | * Python递归最大深度为1000,且不支持尾递归优化 146 | * Python中应尽量避免递归 147 | 148 | == 作用域与全局变量 149 | [%step] 150 | * 作用域:变量生效的范围 151 | * 局部变量: 在函数体内定义的变量,局部变量作用域为函数体 152 | * 全局变量: 定义在函数体外 153 | * 全局变量的作用域: 全局变量在任何地方都是可读的,但需要使用 `global` 关键字申明才可写 154 | * 变量覆盖:小作用域的变量会覆盖大作用域的变量 155 | * 全局变量可以用,但是避免写,忘记 `global` 关键字 156 | 157 | == 文档与docstring 158 | [source,python] 159 | ---- 160 | def fn(): 161 | '''doc string''' # <1> 162 | pass 163 | ---- 164 | <1> 紧接着函数名的,使用三引号 `'''` 包围的字符串称之为docstring, `help` 函数打印的即此字符串 165 | 166 | == 函数作为一等公民 167 | 168 | === 高阶函数 169 | [source,python] 170 | ---- 171 | def add(x, y): 172 | return x + y 173 | 174 | def fold(fn, *args): #<1> 175 | it = iter(args) #<2> 176 | ret = next(it) 177 | for x in it: 178 | ret = fn(ret, x) 179 | return ret 180 | 181 | fold(add, 1, 2, 3, 4, 5) 182 | ---- 183 | <1> 函数作为参数传入,接收函数作为参数的函数称之为 *高阶函数* 184 | <2> `iter` 函数分装迭代器 185 | 186 | === 返回函数 187 | [source,python] 188 | ---- 189 | def external(): 190 | def internal(): 191 | pass 192 | return internal 193 | ---- 194 | 195 | == 装饰器与AOP 196 | 197 | === ! 198 | [source,python] 199 | ---- 200 | import time 201 | 202 | def timeit(fn): 203 | def wrap(*args, **kwargs): 204 | start = time.time() 205 | fn(*args, **kwargs) 206 | print('call {0} spend {1}s'.format(fn.__name__, time.time() - start)) 207 | return wrap 208 | ---- 209 | 210 | 211 | === 使用方法 212 | [source,python] 213 | ---- 214 | def sleep(x): 215 | time.sleep(x) 216 | 217 | fn = timeit(sleep) 218 | fn(0.2) 219 | ---- 220 | 221 | ==== 更好的使用方法 222 | [source,python] 223 | ---- 224 | @timeit # <1> 225 | def sleep(x): 226 | time.sleep(x) 227 | 228 | sleep(0.2) 229 | ---- 230 | <1> `timeit` 函数就是装饰器 231 | 232 | === 装饰器的本质 233 | * 装饰器是一个函数 234 | * 装饰器接受一个函数作为参数 235 | * 装饰器返回一个函数,这个函数是对传入的函数封装了一些额外的操作 236 | 237 | === 带参数的装饰器 238 | [source,python] 239 | ---- 240 | import time 241 | 242 | def timeit(process_time=True): 243 | def _timeit(fn): 244 | def wrap(*args, **kwargs): 245 | time_fn = time.clock if process_time else time.time 246 | start = time_fn() 247 | fn(*args, **kwargs) 248 | print('call {0} spend {1}s'.format(fn.__name__, time_fn) - start)) 249 | return wrap 250 | return _timeit 251 | ---- 252 | 253 | ==== 使用方法 254 | [source,python] 255 | ---- 256 | @timeit(False) 257 | def sleep(x): 258 | time.sleep(x) 259 | ---- 260 | 261 | === 逐步分解 262 | * `_timeit` 函数和上一步不带参数的装饰器一样 263 | * 所以 `timeit` 是一个函数, 这个函数返回一个装饰器 264 | * 所以,带参数的装饰器其实是一个函数,这个函数返回一个装饰器 265 | 266 | === 装饰器的update 267 | [source,python] 268 | ---- 269 | import time 270 | 271 | def timeit(fn): 272 | def wrap(*args, **kwargs): 273 | start = time.time() 274 | fn(*args, **kwargs) 275 | #wrap.__doc__ = fn.__doc__ 276 | #wrap.__name__ = fn.__name__ 277 | print('call {0} spend {1}s'.format(fn.__name__, time.time() - start)) 278 | return wrap 279 | 280 | @timeit 281 | def sleep(x): 282 | '''sleep x scond''' 283 | time.sleep(x) 284 | 285 | help(sleep) 286 | ---- 287 | 288 | === ! 289 | [source,python] 290 | ---- 291 | import time 292 | 293 | def timeit(fn): 294 | def wrap(*args, **kwargs): 295 | start = time.time() 296 | fn(*args, **kwargs) 297 | wrap.__doc__ = fn.__doc__ 298 | wrap.__name__ = fn.__name__ 299 | print('call {0} spend {1}s'.format(fn.__name__, time.time() - start)) 300 | return wrap 301 | 302 | @timeit 303 | def sleep(x): 304 | '''sleep x scond''' 305 | time.sleep(x) 306 | 307 | help(sleep) 308 | ---- 309 | 310 | === 装饰器的update 311 | [source,python] 312 | ---- 313 | import time 314 | import functools 315 | 316 | def timeit(fn): 317 | @functools.wraps #<1> 318 | def wrap(*args, **kwargs): 319 | start = time.time() 320 | fn(*args, **kwargs) 321 | print('call {0} spend {1}s'.format(fn.__name__, time.time() - start)) 322 | return wrap 323 | 324 | @timeit 325 | def sleep(x): 326 | '''sleep x scond''' 327 | time.sleep(x) 328 | 329 | help(sleep) 330 | ---- 331 | <1> 使用 `functools.wraps` 自动update 332 | -------------------------------------------------------------------------------- /presentations/005_面向对象.adoc: -------------------------------------------------------------------------------- 1 | = 面向对象 2 | comyn 3 | v1.0 4 | :source-highlighter: pygments 5 | :revealjs_history: false 6 | :revealjs_center: false 7 | :revealjs_embedded: true 8 | :revealjsdir: ../reveal.js 9 | :imagesdir: ../assets/images/5 10 | :homepage: http://www.magedu.com 11 | 12 | == 编程范式 13 | 14 | [%step] 15 | * 编程范式指的是软件工程中的一种方法学 16 | * 常见的编程范式有:OOP、FP、PP、IP 17 | * 通常每种语言都会提倡一些范式,也有的语言支持多种范式 18 | * Python是一种多范式语言,但是对OOP支持最好 19 | 20 | == OOP的基本概念 21 | 22 | === 基本哲学 23 | 24 | [%step] 25 | * 世界是由对象组成的 26 | * 对象具有运动规律和内部状态 27 | * 对象之间的相互作用和通讯构成世界 28 | 29 | === 对象的特性 30 | 31 | [%step] 32 | * 唯一性:世界上没有两片相同的树叶 33 | * 分类性:分类是对现实世界的抽象 34 | 35 | === OOP的三大特征 36 | 37 | [%step] 38 | * 继承 39 | * 多态 40 | * 封装 41 | 42 | === 面向对象的本质 43 | 44 | [%step] 45 | * 面向对象是对数据和行为的封装 46 | * 但是有时候,数据仅仅是数据,方法仅仅是方法 47 | 48 | == 组织数据 49 | 50 | === ! 51 | 52 | [source,python] 53 | ---- 54 | data = (13, 63, 5, 378, 58, 40) 55 | 56 | def avg(data): 57 | return sum(data) / len(data) 58 | 59 | print(avg(data)) 60 | ---- 61 | 62 | 63 | === 门的例子 64 | 65 | [%step] 66 | * 数据:门牌号、 打开/关闭的状态 67 | * 操作:打开、关闭 68 | 69 | === 过程化的组织方法 70 | 71 | [source,python] 72 | ---- 73 | door1 = [1, 'closed'] 74 | door2 = [1, 'closed'] 75 | 76 | def open_door(door): 77 | door[1] = 'opening' 78 | return door 79 | 80 | def close_door(door): 81 | door[1] = 'close' 82 | return door 83 | ---- 84 | 85 | === 面向对象的组织方法 86 | 87 | [source,python] 88 | ---- 89 | class Door(object): 90 | def __init__(self, number, status): 91 | self.number = number 92 | self.status = status 93 | 94 | def open(self): 95 | self.status = 'opening' 96 | 97 | def close(self): 98 | self.status = 'closed' 99 | ---- 100 | 101 | 102 | == 类的定义与初始化 103 | 104 | === 定义类 105 | 106 | [%step] 107 | [source,python] 108 | ---- 109 | class ClassName: 110 | ---- 111 | 112 | [source,python] 113 | ---- 114 | class ClassName(parents): 115 | ---- 116 | 117 | === 定义方法 118 | 119 | [source,python] 120 | ---- 121 | class ClassName(object): 122 | def method_name(self, args): # <1> <2> 123 | pass 124 | ---- 125 | <1> 第一个参数必须是 `self` 其他的和定义函数没有区别 126 | <2> `self` 是一个变量,指向对象本身。`self` 可以是任意合法的变量名 127 | 128 | === 构造方法 129 | 130 | [source,python] 131 | ---- 132 | class ClassName(object): 133 | def __init__(self, arg): 134 | pass 135 | ---- 136 | 137 | === 实例化 138 | 139 | [source,python] 140 | ---- 141 | instance = ClassName(arg) # <1> 142 | ---- 143 | <1> 对象的实例化,其实是调用了类的构造方法。但是 `self` 参数无需传入,解释器会自动传入。 144 | 145 | === 关于构造函数中的 `self` 146 | 147 | [%step] 148 | * 我们说 `实例化其实是调用构造方法` 149 | * 我们还说 `self指向对象本身` 150 | * 那么,调用构造方法的时候 `self` 是什么鬼? 151 | 152 | === 关于构造函数中的 `self` 153 | 154 | 事实上, `\\__init__` 方法并非实例化时执行的第一个方法。当Python实例化一个对象时, 首先调用的是 `\\__new__` 方法,`\\__new__` 方法的第一个参数指向类本身。并且返回类的一个实例。 这个实例正是传递给 `\\__init__` 的 `self` 。所以严格的讲,`\\__new__` 方法才是真正创建实例的方法, 而 `\\__init__` 方法只是初始化实例的数据。 155 | 156 | 157 | == 访问控制 158 | 159 | === 实例变量和实例方法 160 | 161 | * 任意实例方法内都可以定义定义实例变量, 通常在构造方法中定义 162 | * 定义在类中、不加任何装饰器,第一个参数是 `self` 的方法都叫做实例方法 163 | * 实例变量和实例方法绑定到特定的实例 164 | 165 | === 私有成员 166 | 167 | * 以双下划线开始 168 | * 不以双下划线结束 169 | 170 | === 类变量和类方法 171 | 172 | * 类变量定义在所有方法之外 173 | * 类方法使用 `@classmethod` 装饰器装饰 174 | * 类方法的第一个参数指向类本身, 通常使用 `cls` 命名 175 | * 相对于实例变量和实例方法, 类变量和类方法绑定到特定的类 176 | 177 | === 静态方法 178 | 179 | * 使用 `@staticmethod` 装饰器装饰 180 | * 首参无特殊要求 181 | * 静态方法和普通的函数没有区别 182 | 183 | === 属性 184 | 185 | * 使用 `@property`装饰器装饰的方法 186 | * 属性有 `getter` 、 `setter` 和 `deleter` 187 | 188 | == 继承 189 | 190 | === 单继承 191 | 192 | [source,python] 193 | ---- 194 | class A(object): 195 | pass 196 | 197 | class B(A): 198 | pass 199 | ---- 200 | 201 | === 重写与super 202 | * 子类中定义父类的同名方法,称之为重写 203 | * 子类中调用父类的方法, 使用super对象 204 | * super对象使用super方法生成 205 | 206 | === 多继承 207 | 208 | [source,python] 209 | ---- 210 | class A(object): 211 | pass 212 | 213 | class B(object): 214 | pass 215 | 216 | class C(A, B): 217 | pass 218 | ---- 219 | 220 | === 多继承与方法选取 221 | 222 | [source,python] 223 | ---- 224 | class A(object): 225 | def method(self): 226 | print('method of A') 227 | 228 | class B(object): 229 | def method(self): 230 | print('method of B') 231 | 232 | class C(A, B): 233 | pass 234 | 235 | class D(B, A): 236 | pass 237 | 238 | c = C() 239 | c.method() 240 | 241 | d = D() 242 | d.method() 243 | ---- 244 | 245 | === 多继承与方法选取 246 | 247 | [source,python] 248 | ---- 249 | class A(object): 250 | def method(self): 251 | print('method of A') 252 | 253 | class B(A): 254 | def method(self): 255 | print('method of B') 256 | 257 | class C(A, B): 258 | pass 259 | 260 | class D(B, A): 261 | pass 262 | 263 | c = C() 264 | c.method() 265 | d = D() 266 | d.method() 267 | ---- 268 | 269 | === MRO 270 | 271 | * method resolution order 272 | * 本地优先级: 根据声明顺序从左往右查找 273 | * 单调性:所有子类中,也应满足其查找顺序 274 | 275 | === C3算法 276 | 277 | [source] 278 | ---- 279 | class B(O) -> mro(B) = [B, O] 280 | class B(A1, A2, ...) -> mro(B) = [B] + merge(mro(A1), mro(A2), ... , [A1, A2, ...]) 281 | ---- 282 | 283 | === C3算法的merge步骤 284 | 285 | * 顺序遍历列表 286 | * 首元素满足一下条件,否则遍历下一个序列 287 | ** 在其他序列也是首元素 288 | ** 在其他序列里不存在 289 | * 从所有序列中移除此元素,合并到MRO序列中 290 | * 重复执行,直到所有序列为空或无法执行下去 291 | 292 | === Mixin 293 | 294 | * mixin通过多重集成实现 295 | * mixin是组合的一种方式 296 | * mixin类通常需要满足: 297 | ** 不能单独生成实例 298 | ** 不能继承非Mixin的类 299 | 300 | == 专有方法/魔术方法 301 | 302 | * 总是以双下划线开始 303 | * 总是以双下划线结束 304 | 305 | === 对象创建与销毁 306 | 307 | * `\__new__(cls [, ...])` 创建对象 308 | * `\__init__(self [, ...])` 初始化对象 309 | * `\__del__(self)` 销毁对象时调用 310 | 311 | === 可视化对象 312 | 313 | * `\\__str__(self)` 当调用 `str(obj)` 时调用此方法, 必须返回一个 `str` 314 | * `\\__bytes__(self)` 当调用 `bytes(obj)` 时调用此方法, 必须返回一个 `bytes` 315 | * `\\__repr__(self)` 当调用 `repr(obj)` 时调用此方法,直接print一个对象时,会自动调用 `repr` 方法 316 | 317 | === 比较运算符重载 318 | 319 | [cols="6,2", options="header"] 320 | |=== 321 | |函数原型|运算符 322 | |obj.\\__lt__(self, other)| obj < other 323 | |obj.\\__le__(self, other)| obj \<= other 324 | |obj.\\__eq__(self, other)| obj == other 325 | |obj.\\__ne__(self, other)| obj != other 326 | |obj.\\__gt__(self, other)| obj > other 327 | |obj.\\__ge__(self, other)| obj >= other 328 | |=== 329 | 330 | === `\\__hash__` 与可hash对象 331 | 332 | * 当调用 `hash(obj)` 时, 事实上调用的是 `obj.\\__hash__()` 333 | * 一个对象,实现了 `__hash__(self)` 方法, 称为可hash对象 334 | 335 | 336 | === `\\__bool__` 方法与bool判断 337 | 338 | * `\\__bool__` 方法总是返回 `True` 或 `False` 339 | * 当定义了 `\\__bool__` 方法时, 调用 `bool(obj)` 实际调用的是 `\\__bool__` 方法 340 | * 当未定义 `\\__bool__` 方法时, 调用 `bool(obj)` 会调用 `\\__len__` 方法, 返回0时为False, 非0时为True 341 | * 当 `\\__bool__` 和 `__len__` 都未定义时, `bool(obj)` 永远返回 `True` 342 | * `if` 和 `while` 等语句的条件,如果不是bool类型, 会自动使用 `bool` 方法,转化为bool类型 343 | 344 | === `\\__call__` 与可调用对象 345 | 346 | * 当一个对象实现了 `\\__call__` 方法, 那么它就是一个可调用对象 347 | * 可调用对象可以向函数一样调用 348 | 349 | 350 | === `\\__enter__ \\__exit__` 与 `with` 语句 351 | 352 | * `with` 语法与用途 353 | * `\\__enter__` 方法进入 354 | * `\\__exit__` 方法清理现场 355 | 356 | === 反射 357 | 358 | * `\\__getattr__` 与 `\\__getattribute__` 359 | * `\\__setattr__` 360 | * `\\__delattr__` 361 | * `\\__dir__` 362 | * `\\__dict__` 与 `\\__slots__` 363 | 364 | 365 | === 描述器 366 | 367 | * `\\__get__` 368 | * `\\__set__` 369 | * `\\__delete__` 370 | * 用类实现装饰器 371 | -------------------------------------------------------------------------------- /property_classmethod.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 6, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "class Property:\n", 12 | " def __init__(self, fget=None, fset=None, fdel=None):\n", 13 | " self.fget = fget\n", 14 | " self.fset = fset\n", 15 | " self.fdel = fdel\n", 16 | " \n", 17 | " def __get__(self, instance, cls):\n", 18 | " if self.fget is not None:\n", 19 | " return self.fget(instance)\n", 20 | " else:\n", 21 | " raise AttributeError('property not define getter')\n", 22 | " \n", 23 | " def __set__(self, instance, value):\n", 24 | " if self.fset is not None:\n", 25 | " self.fset(instance, value)\n", 26 | " else:\n", 27 | " raise AttributeError('property not define setter')\n", 28 | " \n", 29 | " def __delete__(self, instance):\n", 30 | " if self.fdel is not None:\n", 31 | " self.fdel(instance)\n", 32 | " else:\n", 33 | " raise AttributeError('property not define deleter')\n", 34 | " \n", 35 | " def setter(self, fset):\n", 36 | " self.fset = fset" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": { 43 | "collapsed": true 44 | }, 45 | "outputs": [], 46 | "source": [ 47 | "Spam.x.__get__(spam, Spam)" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 12, 53 | "metadata": { 54 | "collapsed": true 55 | }, 56 | "outputs": [], 57 | "source": [ 58 | "class Spam:\n", 59 | " def __init__(self, x):\n", 60 | " self.__x = x\n", 61 | " \n", 62 | " #@Property\n", 63 | " def x(self):\n", 64 | " return self.__x\n", 65 | " \n", 66 | " #@x.setter\n", 67 | " def set_x(self, x):\n", 68 | " self.__x = x" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 13, 74 | "metadata": { 75 | "collapsed": false 76 | }, 77 | "outputs": [ 78 | { 79 | "ename": "TypeError", 80 | "evalue": "x() missing 1 required positional argument: 'self'", 81 | "output_type": "error", 82 | "traceback": [ 83 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 84 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 85 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mSpam\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 86 | "\u001b[1;31mTypeError\u001b[0m: x() missing 1 required positional argument: 'self'" 87 | ] 88 | } 89 | ], 90 | "source": [ 91 | "Spam.x()" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": 14, 97 | "metadata": { 98 | "collapsed": true 99 | }, 100 | "outputs": [], 101 | "source": [ 102 | "spam = Spam(6)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": 15, 108 | "metadata": { 109 | "collapsed": false 110 | }, 111 | "outputs": [ 112 | { 113 | "data": { 114 | "text/plain": [ 115 | "6" 116 | ] 117 | }, 118 | "execution_count": 15, 119 | "metadata": {}, 120 | "output_type": "execute_result" 121 | } 122 | ], 123 | "source": [ 124 | "Spam.x(spam)" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": null, 130 | "metadata": { 131 | "collapsed": true 132 | }, 133 | "outputs": [], 134 | "source": [] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": { 140 | "collapsed": true 141 | }, 142 | "outputs": [], 143 | "source": [] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 8, 148 | "metadata": { 149 | "collapsed": true 150 | }, 151 | "outputs": [], 152 | "source": [ 153 | "spam = Spam(3)" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": { 160 | "collapsed": true 161 | }, 162 | "outputs": [], 163 | "source": [] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": 9, 168 | "metadata": { 169 | "collapsed": false 170 | }, 171 | "outputs": [ 172 | { 173 | "data": { 174 | "text/plain": [ 175 | "3" 176 | ] 177 | }, 178 | "execution_count": 9, 179 | "metadata": {}, 180 | "output_type": "execute_result" 181 | } 182 | ], 183 | "source": [ 184 | "spam.x" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": { 191 | "collapsed": true 192 | }, 193 | "outputs": [], 194 | "source": [] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": 10, 199 | "metadata": { 200 | "collapsed": false 201 | }, 202 | "outputs": [], 203 | "source": [ 204 | "spam.x = 4" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": 11, 210 | "metadata": { 211 | "collapsed": false 212 | }, 213 | "outputs": [ 214 | { 215 | "data": { 216 | "text/plain": [ 217 | "4" 218 | ] 219 | }, 220 | "execution_count": 11, 221 | "metadata": {}, 222 | "output_type": "execute_result" 223 | } 224 | ], 225 | "source": [ 226 | "spam.x" 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": 24, 232 | "metadata": { 233 | "collapsed": true 234 | }, 235 | "outputs": [], 236 | "source": [ 237 | "class ClassMethod:\n", 238 | " def __init__(self, fn):\n", 239 | " self.fn = fn\n", 240 | " \n", 241 | " def __get__(self, instance, cls):\n", 242 | " def wrap(*args, **kwargs):\n", 243 | " return self.fn(cls, *args, **kwargs)\n", 244 | " return wrap" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": 32, 250 | "metadata": { 251 | "collapsed": true 252 | }, 253 | "outputs": [], 254 | "source": [ 255 | "class Grok:\n", 256 | " x = '123'\n", 257 | " \n", 258 | " #@ClassMethod\n", 259 | " def method(cls):\n", 260 | " print(cls.x)" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": 34, 266 | "metadata": { 267 | "collapsed": false 268 | }, 269 | "outputs": [ 270 | { 271 | "name": "stdout", 272 | "output_type": "stream", 273 | "text": [ 274 | "123\n" 275 | ] 276 | } 277 | ], 278 | "source": [ 279 | "Grok.method(Grok)" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 29, 285 | "metadata": { 286 | "collapsed": true 287 | }, 288 | "outputs": [], 289 | "source": [ 290 | "grok = Grok()" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": 30, 296 | "metadata": { 297 | "collapsed": false 298 | }, 299 | "outputs": [ 300 | { 301 | "name": "stdout", 302 | "output_type": "stream", 303 | "text": [ 304 | "123\n" 305 | ] 306 | } 307 | ], 308 | "source": [ 309 | "grok.method()" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "metadata": { 316 | "collapsed": true 317 | }, 318 | "outputs": [], 319 | "source": [] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": null, 324 | "metadata": { 325 | "collapsed": true 326 | }, 327 | "outputs": [], 328 | "source": [] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": null, 333 | "metadata": { 334 | "collapsed": true 335 | }, 336 | "outputs": [], 337 | "source": [] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "execution_count": null, 342 | "metadata": { 343 | "collapsed": true 344 | }, 345 | "outputs": [], 346 | "source": [] 347 | } 348 | ], 349 | "metadata": { 350 | "kernelspec": { 351 | "display_name": "Python 3", 352 | "language": "python", 353 | "name": "python3" 354 | }, 355 | "language_info": { 356 | "codemirror_mode": { 357 | "name": "ipython", 358 | "version": 3 359 | }, 360 | "file_extension": ".py", 361 | "mimetype": "text/x-python", 362 | "name": "python", 363 | "nbconvert_exporter": "python", 364 | "pygments_lexer": "ipython3", 365 | "version": "3.4.2" 366 | } 367 | }, 368 | "nbformat": 4, 369 | "nbformat_minor": 0 370 | } 371 | -------------------------------------------------------------------------------- /复习.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 12, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "def info(fn):\n", 12 | " def wrap(*args, **kwargs):\n", 13 | " print(fn.__name__)\n", 14 | " kwargs['message'] = 'fuck {0}'.format(kwargs['message'])\n", 15 | " return fn(*args, **kwargs)\n", 16 | " return wrap" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 13, 22 | "metadata": { 23 | "collapsed": true 24 | }, 25 | "outputs": [], 26 | "source": [ 27 | "@info\n", 28 | "def p(message):\n", 29 | " print(message)" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 14, 35 | "metadata": { 36 | "collapsed": false 37 | }, 38 | "outputs": [ 39 | { 40 | "name": "stdout", 41 | "output_type": "stream", 42 | "text": [ 43 | "p\n", 44 | "fuck test\n" 45 | ] 46 | } 47 | ], 48 | "source": [ 49 | "p(message='test')" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "metadata": { 56 | "collapsed": true 57 | }, 58 | "outputs": [], 59 | "source": [ 60 | "info(p)('test')" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 15, 66 | "metadata": { 67 | "collapsed": true 68 | }, 69 | "outputs": [], 70 | "source": [ 71 | "routes = {}\n", 72 | "def router(url):\n", 73 | " def wrap(fn):\n", 74 | " routes[url] = fn\n", 75 | " return fn\n", 76 | " return wrap" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 18, 82 | "metadata": { 83 | "collapsed": true 84 | }, 85 | "outputs": [], 86 | "source": [ 87 | "@router('/')\n", 88 | "def index():\n", 89 | " print('test')" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 19, 95 | "metadata": { 96 | "collapsed": false 97 | }, 98 | "outputs": [ 99 | { 100 | "data": { 101 | "text/plain": [ 102 | "{'/': }" 103 | ] 104 | }, 105 | "execution_count": 19, 106 | "metadata": {}, 107 | "output_type": "execute_result" 108 | } 109 | ], 110 | "source": [ 111 | "routes" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "metadata": { 118 | "collapsed": true 119 | }, 120 | "outputs": [], 121 | "source": [] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": 17, 126 | "metadata": { 127 | "collapsed": false 128 | }, 129 | "outputs": [ 130 | { 131 | "data": { 132 | "text/plain": [ 133 | "{'/': }" 134 | ] 135 | }, 136 | "execution_count": 17, 137 | "metadata": {}, 138 | "output_type": "execute_result" 139 | } 140 | ], 141 | "source": [ 142 | "routes" 143 | ] 144 | }, 145 | { 146 | "cell_type": "markdown", 147 | "metadata": {}, 148 | "source": [ 149 | "## Context" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": 20, 155 | "metadata": { 156 | "collapsed": true 157 | }, 158 | "outputs": [], 159 | "source": [ 160 | "class Context:\n", 161 | " def __enter__(self):\n", 162 | " print('enter context')\n", 163 | " \n", 164 | " def __exit__(self, *args, **kwargs):\n", 165 | " print('exit context')" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 21, 171 | "metadata": { 172 | "collapsed": false 173 | }, 174 | "outputs": [ 175 | { 176 | "name": "stdout", 177 | "output_type": "stream", 178 | "text": [ 179 | "enter context\n", 180 | "ha ha ha\n", 181 | "exit context\n" 182 | ] 183 | } 184 | ], 185 | "source": [ 186 | "with Context():\n", 187 | " print('ha ha ha')" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": 26, 193 | "metadata": { 194 | "collapsed": true 195 | }, 196 | "outputs": [], 197 | "source": [ 198 | "class Require:\n", 199 | " def __init__(self, perm, env):\n", 200 | " self.perm = perm\n", 201 | " self.env = env\n", 202 | " \n", 203 | " def __enter__(self):\n", 204 | " if self.env.perm!= self.perm:\n", 205 | " raise Exception('require {0}'.format(self.perm))\n", 206 | " \n", 207 | " def __exit__(self, *args, **kwargs):\n", 208 | " pass" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "metadata": { 215 | "collapsed": true 216 | }, 217 | "outputs": [], 218 | "source": [] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": 24, 223 | "metadata": { 224 | "collapsed": true 225 | }, 226 | "outputs": [], 227 | "source": [ 228 | "class Env:\n", 229 | " def __init__(self, perm):\n", 230 | " self.perm = perm" 231 | ] 232 | }, 233 | { 234 | "cell_type": "code", 235 | "execution_count": 28, 236 | "metadata": { 237 | "collapsed": false 238 | }, 239 | "outputs": [ 240 | { 241 | "name": "stdout", 242 | "output_type": "stream", 243 | "text": [ 244 | "i want write something\n" 245 | ] 246 | } 247 | ], 248 | "source": [ 249 | "with Require('write', Env('write')):\n", 250 | " print('i want write something')" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "metadata": { 257 | "collapsed": true 258 | }, 259 | "outputs": [], 260 | "source": [] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": 29, 265 | "metadata": { 266 | "collapsed": true 267 | }, 268 | "outputs": [], 269 | "source": [ 270 | "class A:\n", 271 | " def __init__(self):\n", 272 | " self.x = 0" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 30, 278 | "metadata": { 279 | "collapsed": true 280 | }, 281 | "outputs": [], 282 | "source": [ 283 | "a = A()" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": 31, 289 | "metadata": { 290 | "collapsed": false 291 | }, 292 | "outputs": [ 293 | { 294 | "data": { 295 | "text/plain": [ 296 | "['__class__',\n", 297 | " '__delattr__',\n", 298 | " '__dict__',\n", 299 | " '__dir__',\n", 300 | " '__doc__',\n", 301 | " '__eq__',\n", 302 | " '__format__',\n", 303 | " '__ge__',\n", 304 | " '__getattribute__',\n", 305 | " '__gt__',\n", 306 | " '__hash__',\n", 307 | " '__init__',\n", 308 | " '__le__',\n", 309 | " '__lt__',\n", 310 | " '__module__',\n", 311 | " '__ne__',\n", 312 | " '__new__',\n", 313 | " '__reduce__',\n", 314 | " '__reduce_ex__',\n", 315 | " '__repr__',\n", 316 | " '__setattr__',\n", 317 | " '__sizeof__',\n", 318 | " '__str__',\n", 319 | " '__subclasshook__',\n", 320 | " '__weakref__',\n", 321 | " 'x']" 322 | ] 323 | }, 324 | "execution_count": 31, 325 | "metadata": {}, 326 | "output_type": "execute_result" 327 | } 328 | ], 329 | "source": [ 330 | "dir(a)" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": 32, 336 | "metadata": { 337 | "collapsed": false 338 | }, 339 | "outputs": [ 340 | { 341 | "data": { 342 | "text/plain": [ 343 | "0" 344 | ] 345 | }, 346 | "execution_count": 32, 347 | "metadata": {}, 348 | "output_type": "execute_result" 349 | } 350 | ], 351 | "source": [ 352 | "a.x" 353 | ] 354 | }, 355 | { 356 | "cell_type": "code", 357 | "execution_count": 33, 358 | "metadata": { 359 | "collapsed": false 360 | }, 361 | "outputs": [ 362 | { 363 | "data": { 364 | "text/plain": [ 365 | "0" 366 | ] 367 | }, 368 | "execution_count": 33, 369 | "metadata": {}, 370 | "output_type": "execute_result" 371 | } 372 | ], 373 | "source": [ 374 | "getattr(a, 'x')" 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": 34, 380 | "metadata": { 381 | "collapsed": true 382 | }, 383 | "outputs": [], 384 | "source": [ 385 | "class ConfigValues:\n", 386 | " def __init__(self):\n", 387 | " self.a = 0\n", 388 | " self.b = 1" 389 | ] 390 | }, 391 | { 392 | "cell_type": "markdown", 393 | "metadata": {}, 394 | "source": [ 395 | "xxxxx = a" 396 | ] 397 | }, 398 | { 399 | "cell_type": "markdown", 400 | "metadata": {}, 401 | "source": [ 402 | "cfg.get('xxxx')" 403 | ] 404 | }, 405 | { 406 | "cell_type": "code", 407 | "execution_count": null, 408 | "metadata": { 409 | "collapsed": true 410 | }, 411 | "outputs": [], 412 | "source": [ 413 | "getattr(ConfigValues(), cfg.get('xxxxx'), default)" 414 | ] 415 | }, 416 | { 417 | "cell_type": "markdown", 418 | "metadata": {}, 419 | "source": [ 420 | "getattr(matcher, 'metch', default)" 421 | ] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "execution_count": null, 426 | "metadata": { 427 | "collapsed": true 428 | }, 429 | "outputs": [], 430 | "source": [] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": null, 435 | "metadata": { 436 | "collapsed": true 437 | }, 438 | "outputs": [], 439 | "source": [] 440 | }, 441 | { 442 | "cell_type": "code", 443 | "execution_count": null, 444 | "metadata": { 445 | "collapsed": true 446 | }, 447 | "outputs": [], 448 | "source": [] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "execution_count": null, 453 | "metadata": { 454 | "collapsed": true 455 | }, 456 | "outputs": [], 457 | "source": [] 458 | }, 459 | { 460 | "cell_type": "code", 461 | "execution_count": 35, 462 | "metadata": { 463 | "collapsed": true 464 | }, 465 | "outputs": [], 466 | "source": [ 467 | "class Spam:\n", 468 | " x = 0\n", 469 | " \n", 470 | " def method(self):\n", 471 | " pass" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "execution_count": 36, 477 | "metadata": { 478 | "collapsed": true 479 | }, 480 | "outputs": [], 481 | "source": [ 482 | "spam = Spam()" 483 | ] 484 | }, 485 | { 486 | "cell_type": "code", 487 | "execution_count": null, 488 | "metadata": { 489 | "collapsed": true 490 | }, 491 | "outputs": [], 492 | "source": [ 493 | "spam.x -> Spam.x.__get__(spam, Spam)\n", 494 | "spam.x = value -> Spam.x.__set__(spam, value)\n", 495 | "del spam.x -> Spam.x.__delete__(spam)" 496 | ] 497 | }, 498 | { 499 | "cell_type": "code", 500 | "execution_count": 61, 501 | "metadata": { 502 | "collapsed": true 503 | }, 504 | "outputs": [], 505 | "source": [ 506 | "class Positive:\n", 507 | " def __init__(self, name):\n", 508 | " self.name = name\n", 509 | " \n", 510 | " def __set__(self, instance, value):\n", 511 | " if value < 0:\n", 512 | " raise Exception('{0} must be positive')\n", 513 | " instance.__dict__[self.name] = value\n", 514 | "\n", 515 | " def __get__(self, instance, cls):\n", 516 | " #return instance.__dict__[self.name]\n", 517 | " return 0" 518 | ] 519 | }, 520 | { 521 | "cell_type": "code", 522 | "execution_count": null, 523 | "metadata": { 524 | "collapsed": true 525 | }, 526 | "outputs": [], 527 | "source": [] 528 | }, 529 | { 530 | "cell_type": "code", 531 | "execution_count": 62, 532 | "metadata": { 533 | "collapsed": true 534 | }, 535 | "outputs": [], 536 | "source": [ 537 | "class Point:\n", 538 | " x = Positive('x')\n", 539 | " y = Positive('y')\n", 540 | " \n", 541 | " def __init__(self, x, y):\n", 542 | " self.x = x\n", 543 | " self.y = y\n", 544 | "\n", 545 | " " 546 | ] 547 | }, 548 | { 549 | "cell_type": "code", 550 | "execution_count": null, 551 | "metadata": { 552 | "collapsed": true 553 | }, 554 | "outputs": [], 555 | "source": [] 556 | }, 557 | { 558 | "cell_type": "code", 559 | "execution_count": 63, 560 | "metadata": { 561 | "collapsed": false 562 | }, 563 | "outputs": [], 564 | "source": [ 565 | "p = Point(3, 5)" 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "execution_count": 64, 571 | "metadata": { 572 | "collapsed": false 573 | }, 574 | "outputs": [ 575 | { 576 | "data": { 577 | "text/plain": [ 578 | "0" 579 | ] 580 | }, 581 | "execution_count": 64, 582 | "metadata": {}, 583 | "output_type": "execute_result" 584 | } 585 | ], 586 | "source": [ 587 | "p.x" 588 | ] 589 | }, 590 | { 591 | "cell_type": "code", 592 | "execution_count": 65, 593 | "metadata": { 594 | "collapsed": true 595 | }, 596 | "outputs": [], 597 | "source": [ 598 | "p.x = 1000000" 599 | ] 600 | }, 601 | { 602 | "cell_type": "code", 603 | "execution_count": 66, 604 | "metadata": { 605 | "collapsed": false 606 | }, 607 | "outputs": [ 608 | { 609 | "data": { 610 | "text/plain": [ 611 | "0" 612 | ] 613 | }, 614 | "execution_count": 66, 615 | "metadata": {}, 616 | "output_type": "execute_result" 617 | } 618 | ], 619 | "source": [ 620 | "p.x" 621 | ] 622 | }, 623 | { 624 | "cell_type": "code", 625 | "execution_count": 67, 626 | "metadata": { 627 | "collapsed": false 628 | }, 629 | "outputs": [ 630 | { 631 | "data": { 632 | "text/plain": [ 633 | "['__class__',\n", 634 | " '__delattr__',\n", 635 | " '__dict__',\n", 636 | " '__dir__',\n", 637 | " '__doc__',\n", 638 | " '__eq__',\n", 639 | " '__format__',\n", 640 | " '__ge__',\n", 641 | " '__getattribute__',\n", 642 | " '__gt__',\n", 643 | " '__hash__',\n", 644 | " '__init__',\n", 645 | " '__le__',\n", 646 | " '__lt__',\n", 647 | " '__module__',\n", 648 | " '__ne__',\n", 649 | " '__new__',\n", 650 | " '__reduce__',\n", 651 | " '__reduce_ex__',\n", 652 | " '__repr__',\n", 653 | " '__setattr__',\n", 654 | " '__sizeof__',\n", 655 | " '__str__',\n", 656 | " '__subclasshook__',\n", 657 | " '__weakref__',\n", 658 | " 'x',\n", 659 | " 'y']" 660 | ] 661 | }, 662 | "execution_count": 67, 663 | "metadata": {}, 664 | "output_type": "execute_result" 665 | } 666 | ], 667 | "source": [ 668 | "dir(p)" 669 | ] 670 | }, 671 | { 672 | "cell_type": "code", 673 | "execution_count": 68, 674 | "metadata": { 675 | "collapsed": false 676 | }, 677 | "outputs": [ 678 | { 679 | "data": { 680 | "text/plain": [ 681 | "{'x': 1000000, 'y': 5}" 682 | ] 683 | }, 684 | "execution_count": 68, 685 | "metadata": {}, 686 | "output_type": "execute_result" 687 | } 688 | ], 689 | "source": [ 690 | "p.__dict__" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "execution_count": null, 696 | "metadata": { 697 | "collapsed": true 698 | }, 699 | "outputs": [], 700 | "source": [] 701 | }, 702 | { 703 | "cell_type": "code", 704 | "execution_count": 59, 705 | "metadata": { 706 | "collapsed": false 707 | }, 708 | "outputs": [ 709 | { 710 | "name": "stdout", 711 | "output_type": "stream", 712 | "text": [ 713 | ".x.__get__(<__main__.Point object at 0x7fdfc805e2b0>, )\n" 714 | ] 715 | }, 716 | { 717 | "data": { 718 | "text/plain": [ 719 | "3" 720 | ] 721 | }, 722 | "execution_count": 59, 723 | "metadata": {}, 724 | "output_type": "execute_result" 725 | } 726 | ], 727 | "source": [ 728 | "p.x # -> Point.x.__get__(p, Point)" 729 | ] 730 | }, 731 | { 732 | "cell_type": "code", 733 | "execution_count": 44, 734 | "metadata": { 735 | "collapsed": false 736 | }, 737 | "outputs": [ 738 | { 739 | "data": { 740 | "text/plain": [ 741 | "5" 742 | ] 743 | }, 744 | "execution_count": 44, 745 | "metadata": {}, 746 | "output_type": "execute_result" 747 | } 748 | ], 749 | "source": [ 750 | "p.y" 751 | ] 752 | }, 753 | { 754 | "cell_type": "code", 755 | "execution_count": 60, 756 | "metadata": { 757 | "collapsed": false 758 | }, 759 | "outputs": [ 760 | { 761 | "ename": "Exception", 762 | "evalue": "{0} must be positive", 763 | "output_type": "error", 764 | "traceback": [ 765 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 766 | "\u001b[1;31mException\u001b[0m Traceback (most recent call last)", 767 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m-\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 768 | "\u001b[1;32m\u001b[0m in \u001b[0;36m__set__\u001b[1;34m(self, instance, value)\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__set__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0minstance\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mvalue\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'{0} must be positive'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 8\u001b[0m \u001b[0minstance\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__dict__\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", 769 | "\u001b[1;31mException\u001b[0m: {0} must be positive" 770 | ] 771 | } 772 | ], 773 | "source": [ 774 | "p.x = -3" 775 | ] 776 | }, 777 | { 778 | "cell_type": "code", 779 | "execution_count": null, 780 | "metadata": { 781 | "collapsed": true 782 | }, 783 | "outputs": [], 784 | "source": [ 785 | "class Entity:\n", 786 | " id = Column('id', type=int, unique=True)" 787 | ] 788 | }, 789 | { 790 | "cell_type": "code", 791 | "execution_count": 69, 792 | "metadata": { 793 | "collapsed": true 794 | }, 795 | "outputs": [], 796 | "source": [ 797 | "class A:\n", 798 | " @staticmethod\n", 799 | " def a():\n", 800 | " print('A.a')" 801 | ] 802 | }, 803 | { 804 | "cell_type": "code", 805 | "execution_count": 70, 806 | "metadata": { 807 | "collapsed": false 808 | }, 809 | "outputs": [ 810 | { 811 | "name": "stdout", 812 | "output_type": "stream", 813 | "text": [ 814 | "A.a\n" 815 | ] 816 | } 817 | ], 818 | "source": [ 819 | "A.a()" 820 | ] 821 | }, 822 | { 823 | "cell_type": "code", 824 | "execution_count": null, 825 | "metadata": { 826 | "collapsed": true 827 | }, 828 | "outputs": [], 829 | "source": [] 830 | } 831 | ], 832 | "metadata": { 833 | "kernelspec": { 834 | "display_name": "Python 3", 835 | "language": "python", 836 | "name": "python3" 837 | }, 838 | "language_info": { 839 | "codemirror_mode": { 840 | "name": "ipython", 841 | "version": 3 842 | }, 843 | "file_extension": ".py", 844 | "mimetype": "text/x-python", 845 | "name": "python", 846 | "nbconvert_exporter": "python", 847 | "pygments_lexer": "ipython3", 848 | "version": "3.4.2" 849 | } 850 | }, 851 | "nbformat": 4, 852 | "nbformat_minor": 0 853 | } 854 | --------------------------------------------------------------------------------