{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 共有,私有和特殊方法和属性" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 我们之前已经见过 `special` 方法和属性,即以 `__` 开头和结尾的方法和属性\n", "- 私有方法和属性,以 `_` 开头,不过不是真正私有,而是可以调用的,但是不会被代码自动完成所记录(即 Tab 键之后不会显示)\n", "- 其他都是共有的方法和属性\n", "- 以 `__` 开头不以 `__` 结尾的属性是更加特殊的方法,调用方式也不同:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class MyClass(object):\n", " def __init__(self):\n", " print \"I'm special!\"\n", " def _private(self):\n", " print \"I'm private!\"\n", " def public(self):\n", " print \"I'm public!\"\n", " def __really_special(self):\n", " print \"I'm really special!\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm special!\n" ] } ], "source": [ "m = MyClass()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm public!\n" ] } ], "source": [ "m.public()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm private!\n" ] } ], "source": [ "m._private()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "注意调用方式:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm really special!\n" ] } ], "source": [ "m._MyClass__really_special()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }