<!DOCTYPE html>
<html lang="zh-Hans">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=5">
    <title>Python 从Zero 到 Hero（三） | 云图网</title>
    <meta name="keywords" content="https,数据结构">
<meta name="description" content="  封装：隐藏信息   封装是在面向对象编程中一种限制直接访问对象数据以及方法的机制，用来约束对这些数据或方法的操作。   也就是说，封装可以用来隐藏数据成员和成员函数。在此定义下，封装意着一个对象的内部表示在对象之外通常是隐藏的。   对象的所有内部表现是在外部隐藏的，只有对象可以与其内部数据交互。   首先，我们需…">
<meta property="og:type" content="article">
<meta property="og:url" content="https://blog.ytso.com/tech/pnotes/257194.html">
<meta property="og:site_name" content="云图网">
<meta property="og:title" content="Python 从Zero 到 Hero（三）">
<meta property="og:image" content="http://ytso-blog-oss-img.oss-accelerate.aliyuncs.com/wp-content/uploads/2022/05/18/20220518164807929.jpg">
<meta property="og:description" content="  封装：隐藏信息   封装是在面向对象编程中一种限制直接访问对象数据以及方法的机制，用来约束对这些数据或方法的操作。   也就是说，封装可以用来隐藏数据成员和成员函数。在此定义下，封装意着一个对象的内部表示在对象之外通常是隐藏的。   对象的所有内部表现是在外部隐藏的，只有对象可以与其内部数据交互。   首先，我们需…">
<link rel="canonical" href="https://blog.ytso.com/tech/pnotes/257194.html">
<meta name="applicable-device" content="pc,mobile">
<meta http-equiv="Cache-Control" content="no-transform">
<link rel="shortcut icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg">
<link rel='dns-prefetch' href='//cdnjs.cloudflare.com' />
<style id='wp-img-auto-sizes-contain-inline-css' type='text/css'>
img:is([sizes=auto i],[sizes^="auto," i]){contain-intrinsic-size:3000px 1500px}
/*# sourceURL=wp-img-auto-sizes-contain-inline-css */
</style>
<link rel='stylesheet' id='stylesheet-css' href='https://blog.ytso.com/wp-content/themes/justnews/css/style.css?ver=6.21.5' type='text/css' media='all' />
<link rel='stylesheet' id='material-icons-css' href='https://blog.ytso.com/wp-content/themes/justnews/themer/assets/css/material-icons.css?ver=6.21.5' type='text/css' media='all' />
<link rel='stylesheet' id='remixicon-css' href='https://cdnjs.cloudflare.com/ajax/libs/remixicon/4.2.0/remixicon.min.css?ver=6.9.4' type='text/css' media='all' />
<link rel='stylesheet' id='font-awesome-css' href='https://blog.ytso.com/wp-content/themes/justnews/themer/assets/css/font-awesome.css?ver=6.21.5' type='text/css' media='all' />
<style id='wp-block-library-inline-css' type='text/css'>
:root{--wp-block-synced-color:#7a00df;--wp-block-synced-color--rgb:122,0,223;--wp-bound-block-color:var(--wp-block-synced-color);--wp-editor-canvas-background:#ddd;--wp-admin-theme-color:#007cba;--wp-admin-theme-color--rgb:0,124,186;--wp-admin-theme-color-darker-10:#006ba1;--wp-admin-theme-color-darker-10--rgb:0,107,160.5;--wp-admin-theme-color-darker-20:#005a87;--wp-admin-theme-color-darker-20--rgb:0,90,135;--wp-admin-border-width-focus:2px}@media (min-resolution:192dpi){:root{--wp-admin-border-width-focus:1.5px}}.wp-element-button{cursor:pointer}:root .has-very-light-gray-background-color{background-color:#eee}:root .has-very-dark-gray-background-color{background-color:#313131}:root .has-very-light-gray-color{color:#eee}:root .has-very-dark-gray-color{color:#313131}:root .has-vivid-green-cyan-to-vivid-cyan-blue-gradient-background{background:linear-gradient(135deg,#00d084,#0693e3)}:root .has-purple-crush-gradient-background{background:linear-gradient(135deg,#34e2e4,#4721fb 50%,#ab1dfe)}:root .has-hazy-dawn-gradient-background{background:linear-gradient(135deg,#faaca8,#dad0ec)}:root .has-subdued-olive-gradient-background{background:linear-gradient(135deg,#fafae1,#67a671)}:root .has-atomic-cream-gradient-background{background:linear-gradient(135deg,#fdd79a,#004a59)}:root .has-nightshade-gradient-background{background:linear-gradient(135deg,#330968,#31cdcf)}:root .has-midnight-gradient-background{background:linear-gradient(135deg,#020381,#2874fc)}:root{--wp--preset--font-size--normal:16px;--wp--preset--font-size--huge:42px}.has-regular-font-size{font-size:1em}.has-larger-font-size{font-size:2.625em}.has-normal-font-size{font-size:var(--wp--preset--font-size--normal)}.has-huge-font-size{font-size:var(--wp--preset--font-size--huge)}.has-text-align-center{text-align:center}.has-text-align-left{text-align:left}.has-text-align-right{text-align:right}.has-fit-text{white-space:nowrap!important}#end-resizable-editor-section{display:none}.aligncenter{clear:both}.items-justified-left{justify-content:flex-start}.items-justified-center{justify-content:center}.items-justified-right{justify-content:flex-end}.items-justified-space-between{justify-content:space-between}.screen-reader-text{border:0;clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal!important}.screen-reader-text:focus{background-color:#ddd;clip-path:none;color:#444;display:block;font-size:1em;height:auto;left:5px;line-height:normal;padding:15px 23px 14px;text-decoration:none;top:5px;width:auto;z-index:100000}html :where(.has-border-color){border-style:solid}html :where([style*=border-top-color]){border-top-style:solid}html :where([style*=border-right-color]){border-right-style:solid}html :where([style*=border-bottom-color]){border-bottom-style:solid}html :where([style*=border-left-color]){border-left-style:solid}html :where([style*=border-width]){border-style:solid}html :where([style*=border-top-width]){border-top-style:solid}html :where([style*=border-right-width]){border-right-style:solid}html :where([style*=border-bottom-width]){border-bottom-style:solid}html :where([style*=border-left-width]){border-left-style:solid}html :where(img[class*=wp-image-]){height:auto;max-width:100%}:where(figure){margin:0 0 1em}html :where(.is-position-sticky){--wp-admin--admin-bar--position-offset:var(--wp-admin--admin-bar--height,0px)}@media screen and (max-width:600px){html :where(.is-position-sticky){--wp-admin--admin-bar--position-offset:0px}}
/*wp_block_styles_on_demand_placeholder:69cbbb3246be2*/
/*# sourceURL=wp-block-library-inline-css */
</style>
<style id='classic-theme-styles-inline-css' type='text/css'>
/*! This file is auto-generated */
.wp-block-button__link{color:#fff;background-color:#32373c;border-radius:9999px;box-shadow:none;text-decoration:none;padding:calc(.667em + 2px) calc(1.333em + 2px);font-size:1.125em}.wp-block-file__button{background:#32373c;color:#fff;text-decoration:none}
/*# sourceURL=/wp-includes/css/classic-themes.min.css */
</style>
<link rel='stylesheet' id='wpcom-member-css' href='https://blog.ytso.com/wp-content/plugins/wpcom-member/css/style.css?ver=1.7.19' type='text/css' media='all' />
<script type="text/javascript" src="https://blog.ytso.com/wp-includes/js/jquery/jquery.min.js?ver=3.7.1" id="jquery-core-js"></script>
<script type="text/javascript" src="https://blog.ytso.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=3.4.1" id="jquery-migrate-js"></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="https://blog.ytso.com/xmlrpc.php?rsd" />
<meta name='description' content=' 封装：隐藏信息 封装是在面向对象编程中一种限制直接访问对象数据以及方法的机制，用来约束对这些数据或方法的操作。 也就是说，封装可以用来隐藏数据成员和成员函数。在此定义下，封装意着一个对象的内部表示在对…' />
<meta name='keywords' content='https,数据结构' />
<style>:root{--theme-color: #08c; --theme-hover: #07c; --logo-height: 32px; --logo-height-mobile: 26px; --menu-item-gap: 28px; --member-login-bg: url('https://blog.ytso.com/loginwall.jpg'); --header-bg-color: #fff; --header-bg-image: none; --theme-border-radius-s: 3px; --theme-border-radius-m: 5px; --theme-border-radius-l: 8px; --theme-border-radius-xl: 12px; --thumb-ratio-default: 480 / 300; --thumb-ratio-post: 480 / 300; --post-video-ratio: 860 / 482;}</style>
<link rel="icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" sizes="32x32" />
<link rel="icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" sizes="192x192" />
<link rel="apple-touch-icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" />
<meta name="msapplication-TileImage" content="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" />
    <!--[if lte IE 11]><script src="https://blog.ytso.com/wp-content/themes/justnews/js/update.js"></script><![endif]-->
</head>
<body class="wp-singular post-template-default single single-post postid-257194 single-format-standard wp-theme-justnews lang-cn el-boxed header-fixed">
<header class="header header-fluid">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" aria-label="menu">
                <span class="icon-bar icon-bar-1"></span>
                <span class="icon-bar icon-bar-2"></span>
                <span class="icon-bar icon-bar-3"></span>
            </button>
                        <div class="logo">
                <a href="https://blog.ytso.com/" rel="home">
                    <img src="https://imgcdn.ytso.com/wp-content/uploads/2021/12/20211207181156143.png" alt="云图网">
                </a>
            </div>
        </div>
        <div class="collapse navbar-collapse mobile-style-0">
            <nav class="primary-menu"><ul id="menu-justnews-footer-menu" class="nav navbar-nav wpcom-adv-menu"><li class="menu-item current-post-ancestor current-post-parent active"><a href="https://blog.ytso.com/category/industrynews">业界资讯</a></li>
<li class="menu-item current-post-ancestor active menu-item-style menu-item-style-1 dropdown"><a target="_blank" href="https://blog.ytso.com/category/tech" class="dropdown-toggle">技术专区</a>
<ul class="dropdown-menu menu-item-wrap menu-item-col-5">
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/cloud">云计算</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/ai">人工智能</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/safety">信息安全</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/bigdata">大数据</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/dev">研发管理</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/webdev">大前端</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/opensource">开源</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/aiops">智能运维</a></li>
	<li class="menu-item current-post-ancestor current-post-parent active"><a href="https://blog.ytso.com/category/tech/pnotes">编程笔记</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/wp">WordPress</a></li>
</ul>
</li>
<li class="menu-item"><a href="https://blog.ytso.com/category/enterprise-strategic-planning">企业战略规划</a></li>
<li class="menu-item"><a href="https://blog.ytso.com/category/download">下载专区</a></li>
<li class="menu-item"><a href="https://blog.ytso.com/category/it%e6%b1%9f%e6%b9%96%e5%8f%b2">江湖史</a></li>
<li class="menu-item"><a href="https://blog.ytso.com/category/notes">随笔记录</a></li>
</ul></nav>            <div class="navbar-action">
                <div class="navbar-search-icon j-navbar-search"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-search"></use></svg></i></div><form class="navbar-search" action="https://blog.ytso.com/" method="get" role="search"><div class="navbar-search-inner"><i class="wpcom-icon wi navbar-search-close"><svg aria-hidden="true"><use xlink:href="#wi-close"></use></svg></i><input type="text" name="s" class="navbar-search-input" autocomplete="off" maxlength="100" placeholder="输入关键词搜索..." value=""><button class="navbar-search-btn" type="submit" aria-label="搜索"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-search"></use></svg></i></button></div></form>                    <div id="j-user-wrap">
                        <a class="login" href="https://blog.ytso.com/login">登录</a>
                        <a class="login register" href="https://blog.ytso.com/register">注册</a>
                    </div>
                                            <a class="wpcom-btn btn-primary btn-xs publish" href="https://blog.ytso.com/contribute">
                            <i class="fa fa-edit"></i> 投稿                        </a>
                                </div>
        </div>
    </div><!-- /.container -->
</header>

<div id="wrap">    <div class="wrap container">
        <ol class="breadcrumb" vocab="https://schema.org/" typeof="BreadcrumbList"><li class="home" property="itemListElement" typeof="ListItem"><a href="https://blog.ytso.com" property="item" typeof="WebPage"><span property="name" class="hide">云图网</span>首页</a><meta property="position" content="1"></li><li property="itemListElement" typeof="ListItem"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-arrow-right-3"></use></svg></i><a href="https://blog.ytso.com/category/industrynews" property="item" typeof="WebPage"><span property="name">业界资讯</span></a><meta property="position" content="2"></li></ol>        <main class="main">
                            <article id="post-257194" class="post-257194 post type-post status-publish format-standard hentry category-industrynews category-pnotes tag-https tag-143 entry">
                    <div class="entry-main">
                                                                        <div class="entry-head">
                            <h1 class="entry-title">Python 从Zero 到 Hero（三）</h1>
                            <div class="entry-info">
                                                                <time class="entry-date published" datetime="2022-05-19T08:58:15+08:00" pubdate>
                                    2022年5月19日 08:58                                </time>
                                <span class="dot">•</span>
                                <a href="https://blog.ytso.com/category/industrynews" rel="category tag">业界资讯</a>, <a href="https://blog.ytso.com/category/tech/pnotes" rel="category tag">编程笔记</a>                                                            </div>
                        </div>
                        
                                                <div class="entry-content text-indent text-justify">
                            <p></p>
<div class="aw-upload-img-list active">
	<a href="http://ytso-blog-oss-img.oss-accelerate.aliyuncs.com/wp-content/uploads/2022/05/18/20220518164807929.jpg" target="_blank" data-fancybox-group="thumb" rel="lightbox noopener"><noscript><img decoding="async" src="http://ytso-blog-oss-img.oss-accelerate.aliyuncs.com/wp-content/uploads/2022/05/18/20220518164807929.jpg" class="img-polaroid" title="1.jpg" alt="1.jpg" /></noscript><img decoding="async" src="https://blog.ytso.com/wp-content/themes/justnews/themer/assets/images/lazy.png" data-original="http://ytso-blog-oss-img.oss-accelerate.aliyuncs.com/wp-content/uploads/2022/05/18/20220518164807929.jpg" class="img-polaroid j-lazy" title="1.jpg" alt="1.jpg" /></a>
</div>
<p> <br /><span style="font-size:15px"><strong>封装：隐藏信息</strong></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">封装是在面向对象编程中一种限制直接访问对象数据以及方法的机制，用来约束对这些数据或方法的操作。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">也就是说，封装可以用来隐藏数据成员和成员函数。在此定义下，封装意着一个对象的内部表示在对象之外通常是隐藏的。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">对象的所有内部表现是在外部隐藏的，只有对象可以与其内部数据交互。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">首先，我们需要了解public与非public实例和方法是如何工作的。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"><strong>公共实例变量</strong></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">对于Python类，我们可以在构造方法中初始化一个public instance variable— 公共实例变量。我们来看以下代码：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在构造函数方法中：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class Person:</span><br /><span style="font-size:15px">   def __init__(self, first_name):</span><br /><span style="font-size:15px">       self.first_name = first_name</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在这里，我们把first_name做为一个参数应用于public instance variable。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">raymond = Person('Raymond');</span><br /><span style="font-size:15px">print(raymond.first_name) # => Raymond</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在类中：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class Person:</span><br /><span style="font-size:15px">  first_name = 'Raymond';</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在这里，我们无需将first_name做为参数，所有的实例对象都有一个通用的类属性 first_name 值初始化为 Raymond。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">请看如下代码：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">ex = Person();</span><br /><span style="font-size:15px">print(ex.first_name) #=>Raymond</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">现在我们已经学习到，可以用公共实例变量和类属性。</span><br /><span style="font-size:15px">有关public另一部分有趣的事情是我们可以管理变量值。这是啥意思？ 我们的对象可以管理变量值： get和set变量值。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">保持 Person 类的思路 ，我们想改变first_name的值。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">ex = Person('Raymond')</span><br /><span style="font-size:15px">ex.first_name = 'Jason'</span><br /><span style="font-size:15px">print(ex.first_name) # => Jason</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">上面我们就为first_name实例变量设置了一个新值，就是这么简单。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"><strong>非公共实例变量</strong></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在这儿，我们没有使用术语“Private”，因为在Python中没有任何属性是真正私有的（通常情况下没有必要）。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">作为通用实例变量，我们可以在构造方法内或类内部定义非全局实例的变量。语法不同之处在于：对于非全局实例变量，请在变量名之前加下划线（_）。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">其实在Python中不存在除了对象内部不能访问的“私有”实例变量。 但是，大多数的Python代码都有一个约定：前缀加下划线（如_spam）为命名的变量被视为API中非公开的内容（无论是函数，方法还是数据成员）——这是来自Python软件基金会之定义。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">我们一起来看代码实例：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class Person:</span><br /><span style="font-size:15px">  def__init__(self,first_name,email):</span><br /><span style="font-size:15px">self.first_name= first_name</span><br /><span style="font-size:15px">self._email =email</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">您有看到emial变量吗？它被定义成一个非公共变量。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">ex = Person(‘raymond’,’<a href="https://www.21cto.com/article/mailto:raymond@21cto.com">raymond@21cto.com</a>’)</span><br /><span style="font-size:15px">print(ex._email) # <a href="https://www.21cto.com/article/mailto:raymond@21cto.com">raymond@21cto.com</a></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">我们可以访问和更新它。非全局实例变量只有一个区别，应该被视为API的非公开部分。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">因此，我们在类中定义和实现两个方法（email和update_email）来访问更新，如下代码：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class Person:</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">  def__init__(self,first_name,email):</span><br /><span style="font-size:15px">     self.first_name = first_name</span><br /><span style="font-size:15px">     self._email = email</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">  defupdate_email(self,new_email):</span><br /><span style="font-size:15px">     self._email = new_email</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">  defemail(self):</span><br /><span style="font-size:15px">     return self._email</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">现在我们可以更新并访问非全局实例变量，使用如下方法。来看下面的代码：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">ex = Person('raymond','<a href="https://www.21cto.com/article/mailto:raymond@21cto.com">raymond@21cto.com</a>')</span><br /><span style="font-size:15px">print(ex.email()) # => <a href="https://www.21cto.com/article/mailto:raymond@21cto.com">raymond@21cto.com</a></span><br /><span style="font-size:15px">ex._email = '<a href="https://www.21cto.com/article/mailto:raymond1@21cto.com">raymond1@21cto.com</a>'</span><br /><span style="font-size:15px">print(ex.email()) # => <a href="https://www.21cto.com/article/mailto:raymond@21cto.com">raymond@21cto.com</a></span><br /><span style="font-size:15px">ex.update_email('<a href="https://www.21cto.com/article/mailto:raymond1@21cto.com">raymond1@21cto.com</a>')</span><br /><span style="font-size:15px">print(ex.email()) # =><a href="https://www.21cto.com/article/mailto:raymond1@21cto.com">raymond1@21cto.com</a></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">1 我们初始化了一个新对象first_name 为 raymond 以及 email 为 <a href="https://www.21cto.com/article/mailto:raymond@21cto.com">raymond@21cto.com</a></span><br /><span style="font-size:15px">2 使用一个方法访问并打印了非全局实例变量 email</span><br /><span style="font-size:15px">3 尝试在我们的类里设置一个新mail</span><br /><span style="font-size:15px">4 我们需要将非全局实例变量视为API的非全局部分</span><br /><span style="font-size:15px">5 用我们的实例方法更新 非全局变量</span><br /><span style="font-size:15px">6 成功！我们可以使用helper方法在我们的类中更新它</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"><strong>公共方法</strong></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在公共方法中，我们可以在类中使用它们：</span><br /><span style="font-size:15px">class Person:</span><br /><span style="font-size:15px">   def __init__(self, first_name, age):</span><br /><span style="font-size:15px">       self.first_name = first_name</span><br /><span style="font-size:15px">       self._age = age</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">   def show_age(self):</span><br /><span style="font-size:15px">       return self._age</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">我们来测试一下：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">raymond = Person('Rayond', 38)</span><br /><span style="font-size:15px">print(raymond.show_age()) # => 38</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">非常好，我们使用它没有任何问题。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"><strong>非公共方法</strong></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">如果声明为非公共方法，我们就不能随意调用了。我们实现相同的Person类，现在我们把show_age加上下划线（_）。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class Person:</span><br /><span style="font-size:15px">   def __init__(self, first_name, age):</span><br /><span style="font-size:15px">       self.first_name = first_name</span><br /><span style="font-size:15px">       self._age = age</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"><strong>    def _show_age(self):</strong></span><br /><span style="font-size:15px">       return self._age</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">现在，我们尝试创建新对象来调用这个非公共方法：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">raymond = Person('Raymond', 38)</span><br /><span style="font-size:15px">print(raymond._show_age()) # => 38</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">我们可以正常访问和更新值。非公共方法只是一个约定惯例，但通常视为API的非公开部分。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">下面是我们如何使用它的一个示例：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class Person:</span><br /><span style="font-size:15px">   def __init__(self, first_name, age):</span><br /><span style="font-size:15px">       self.first_name = first_name</span><br /><span style="font-size:15px">       self._age = age</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">   def show_age(self):</span><br /><span style="font-size:15px">       return self._get_age()</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">   def _get_age(self):</span><br /><span style="font-size:15px">       return self._age</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">raymond = Person('Raymond', 38)</span><br /><span style="font-size:15px">print(raymond.show_age()) # => 38</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">这里有一个_get_age的非公共方法和一个show_age的公共方法。show_age方法可以被我们的对象（不在我们的类中）使用，而_get_age只能用在我们的类定义里面（在show_age方法中）。但是，作为惯例，亦是如此。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">由此我们总结，通过封装，我们是可以确保对象的内部表示是可以从外部隐藏的。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"><strong>继承：行为和特征</strong></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">某此物体有一些共同之处，比如它们的行为和特征。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">比如，我继承了父亲的一些特征和行为。比如他的眼睛和头发特征，以及他的不耐烦和内向等行为。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在面向对象编程中，类可以继承另一个类的共同特征（数据）和行为（方法）。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">接下来我们来看一个例子，然后我们用Python来实现它。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">我们继续来考虑一下汽车。车轮数量，座位容量以及最高时速都是一辆车的属性。比如一个电动汽车 ElectricCar继承了普通 Car类的相同属性。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">以下是Car汽车类的定义以及属性的定义。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class Car:</span><br /><span style="font-size:15px">   def __init__(self, number_of_wheels, seating_capacity,maximum_velocity):</span><br /><span style="font-size:15px">       self.number_of_wheels = number_of_wheels</span><br /><span style="font-size:15px">       self.seating_capacity = seating_capacity</span><br /><span style="font-size:15px">       self.maximum_velocity = maximum_velocity</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">接下来实现Car的类。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">my_car = Car(4, 5, 250)</span><br /><span style="font-size:15px">print(my_car.number_of_wheels)</span><br /><span style="font-size:15px">print(my_car.seating_capacity)</span><br /><span style="font-size:15px">print(my_car.maximum_velocity)</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">一旦运行，我们可以使用所有创建的实例变量。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">在Python中，我们可以将父类应用于子类中作为参数。ElectricCar可以继承我们的Car类。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">class ElectricCar(Car):</span><br /><span style="font-size:15px">   def __init__(self, number_of_wheels, seating_capacity,maximum_velocity):</span><br /><span style="font-size:15px">       Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity)</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">就是这么方便。我们不需要实现任何其它方法，类已经继承了Car类的所有方法。我们来使用代码证明之：</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">my_electric_car = ElectricCar(4, 5, 250)</span><br /><span style="font-size:15px">print(my_electric_car.number_of_wheels) #=> 4</span><br /><span style="font-size:15px">print(my_electric_car.seating_capacity) #=> 5</span><br /><span style="font-size:15px">print(my_electric_car.maximum_velocity) #=> 250</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">干得漂亮！</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px"><strong>小结</strong></span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">至此，我们已经学到了很多关于Python基础的知识。包括：</span></p>
<ul>
<li><span style="font-size:15px">Python变量的工作方式</span></li>
<li><span style="font-size:15px">Python条件语句如何工作</span></li>
<li><span style="font-size:15px">Python循环（while和for）是如何工作的</span></li>
<li><span style="font-size:15px">如何使用列表：Collection与排序</span></li>
<li><span style="font-size:15px">字典键值数据结构</span></li>
<li><span style="font-size:15px">如何遍历以上数据结构</span></li>
<li><span style="font-size:15px">对象和类</span></li>
<li><span style="font-size:15px">属性做为对象的数据</span></li>
<li><span style="font-size:15px">方法做为对象的行为</span></li>
<li><span style="font-size:15px">使用Python设置和获取属性</span></li>
<li><span style="font-size:15px">封装：如何隐藏信息</span></li>
<li><span style="font-size:15px">继承：行为和特征</span></li>
</ul>
<p><span style="font-size:15px"> </span><br /><span style="font-size:15px">祝贺您！我们一起完成为关于Python从入门到应用这一系列密集的内容。</span><br /><span style="font-size:15px"> </span><br /><span style="font-size:15px">有更多关于Python更深入的编程内容，敬请您期待。祝大家生活愉快，不断学习，始终保持最好的编码实践。</span><br /> </p>
<blockquote>
<p><span style="font-size:14px">作者：21CTO社区</span><br /><span style="font-size:14px">说明：Python基础教程：从Zero到Hero连载已完毕。后续还有继续推出相关文章和课程</span></p>
</blockquote>
<p></p>
<div class="entry-readmore"><div class="entry-readmore-btn"></div></div>                                                        <div class="entry-copyright"><p>原创文章，作者：ItWorker，如若转载，请注明出处：https://blog.ytso.com/tech/pnotes/257194.html</p></div>                        </div>

                        <div class="entry-tag"><a href="https://blog.ytso.com/tag/https" rel="tag">https</a><a href="https://blog.ytso.com/tag/%e6%95%b0%e6%8d%ae%e7%bb%93%e6%9e%84" rel="tag">数据结构</a></div>
                        <div class="entry-action">
                            <div class="btn-zan" data-id="257194"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-thumb-up-fill"></use></svg></i> 赞 <span class="entry-action-num">(0)</span></div>
                                                    </div>

                        <div class="entry-bar">
                            <div class="entry-bar-inner">
                                                                <div class="entry-bar-info entry-bar-info2">
                                    <div class="info-item meta">
                                                                                    <a class="meta-item j-heart" href="javascript:;" data-id="257194"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-star"></use></svg></i> <span class="data">0</span></a>                                        <a class="meta-item" href="#comments"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-comment"></use></svg></i> <span class="data">0</span></a>                                                                            </div>
                                    <div class="info-item share">
                                                                                    <a class="meta-item mobile j-mobile-share" href="javascript:;" data-id="257194" data-qrcode="https://blog.ytso.com/tech/pnotes/257194.html">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-share"></use></svg></i> 生成海报                                            </a>
                                                                                    <a class="meta-item wechat" data-share="wechat" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-wechat"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item weibo" data-share="weibo" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-weibo"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item qq" data-share="qq" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-qq"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item qzone" data-share="qzone" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-qzone"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item douban" data-share="douban" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-douban"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item linkedin" data-share="linkedin" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-linkedin"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item facebook" data-share="facebook" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-facebook"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item twitter" data-share="twitter" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-twitter"></use></svg></i>                                            </a>
                                                                            </div>
                                    <div class="info-item act">
                                        <a href="javascript:;" id="j-reading"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-article"></use></svg></i></a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                                            <div class="entry-page">
        <error>
    <code>wp_die</code>
    <title><![CDATA[WordPress &amp;rsaquo; Error]]></title>
    <message><![CDATA[&lt;h1&gt;Error establishing a Redis connection&lt;/h1&gt;
&lt;p&gt;To disable Redis, delete the &lt;code&gt;object-cache.php&lt;/code&gt; file in the &lt;code&gt;/wp-content/&lt;/code&gt; directory.&lt;/p&gt;
]]></message>
    <data>
        <status>500</status>
    </data>
</error>
<!--
Performance optimized by Redis Object Cache. Learn more: https://wprediscache.com

Retrieved 1706 objects (272 KB) from Redis using Predis (v2.4.0).
-->
