面向对象是Python最重要的特性,在Python中一切数据类型都是面向对象的。

1、面向对象概述
面向对象的编程思想是,按照真实世界客观事物的自然规律进行分析,客观世界中存在什么样的实体,构建软件系统就存在什么样的实体。
例如,在真实世界的学校里,会有学生和老师实体,学生有学号、姓名、所在班级等属性(数据),学生还有学习、提问、吃饭和走路等操作。学生只是抽象的描述,这个抽象的描述称为“类”。在学校活动的是学生个体,即张同学、李同学等,这些具体的个体称为“对象”,对象也称为“实例”。
在现实世界有类和对象,软件世界也有面向对象,只不过他们会以某种计算机语言编写的程序代码形式存在,这就是面向对象编程。

2、面向对象三个基本特性
面向对象思想有三个基本特性:封装性、继承性和多态性。

  • 封装性

面向对象的封装使外部访问者不能随意存取对象的内部数据,隐藏了对象的内部细节,只保留有限的对外接口。外部访问者不需要关心对象的内部细节,操作对象变得简单。

  • 继承性

举例,轮船与客船的关系,客船具有轮船的全部特征和行为。
在面向对象中,轮船是一般类,客船是特殊类,特殊类拥有一般类的全部数据和操作,称为特殊类继承一般类。一般类称为“父类”或“超类”,特殊类称为“子类”或“派生类”。

  • 多态性

多态性是指在父类中成员被子类继承之后,可以具有不同的状态或表现行为。

3、类和对象

Python中的数据类型都是类,类是组成Python程序的基本要素,它封装了一类对象的数据和操作。

  • 定义类

Python语言中一个类的实现包括类定义和类体。
类定义语法格式如下:
class 类名 [(父类)]:
类体
其中,class是声明类的关键字,“类名”是自定义的类名,应该遵守Python命名规范,采用大驼峰法命名。“父类”声明当前继承的父类,父类可以省略声明,表示直接继承object类。
演示:

class Student(object):# 类体pass

注意:上述代码声明了一个学生类,它继承了object类,object是所有类的根类,在Python中任何一个类都直接或间接的继承object,所以(object)部分代码可以省略。
pass语句什么操作都不执行,用来维持程序结构的完整,进行占位。

  • 创建和使用对象

一个对象的生命周期包括三个阶段:创建、使用和销毁。销毁对象时Python的垃圾回收机制释放不再使用的内存,不需要程序员负责。程序员只需关心创建和使用对象。
创建对象代码演示:

class Student(object):# 类体passstudent = Student()
print(student)

结果:

解释:Student()表达式创建了一个学生对象,并把创建的对象赋值给student变量,student是指向学生对象的一个引用。通过student变量可以使用刚刚创建的学生对象。print函数打印对象输出。事实上,print函数调用了对象的_str_()方法输出字符串信息,str()方法是object类的一个方法。

  • 实例变量

类成员展示:

#mermaid-svg-Ub0oybpGhsoW07Vy .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .label text{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .node rect,#mermaid-svg-Ub0oybpGhsoW07Vy .node circle,#mermaid-svg-Ub0oybpGhsoW07Vy .node ellipse,#mermaid-svg-Ub0oybpGhsoW07Vy .node polygon,#mermaid-svg-Ub0oybpGhsoW07Vy .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-Ub0oybpGhsoW07Vy .node .label{text-align:center;fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .node.clickable{cursor:pointer}#mermaid-svg-Ub0oybpGhsoW07Vy .arrowheadPath{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-Ub0oybpGhsoW07Vy .flowchart-link{stroke:#333;fill:none}#mermaid-svg-Ub0oybpGhsoW07Vy .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-Ub0oybpGhsoW07Vy .edgeLabel rect{opacity:0.9}#mermaid-svg-Ub0oybpGhsoW07Vy .edgeLabel span{color:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-Ub0oybpGhsoW07Vy .cluster text{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-Ub0oybpGhsoW07Vy .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-Ub0oybpGhsoW07Vy text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-Ub0oybpGhsoW07Vy .actor-line{stroke:grey}#mermaid-svg-Ub0oybpGhsoW07Vy .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-Ub0oybpGhsoW07Vy #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .sequenceNumber{fill:#fff}#mermaid-svg-Ub0oybpGhsoW07Vy #sequencenumber{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy #crosshead path{fill:#333;stroke:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .messageText{fill:#333;stroke:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-Ub0oybpGhsoW07Vy .labelText,#mermaid-svg-Ub0oybpGhsoW07Vy .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-Ub0oybpGhsoW07Vy .loopText,#mermaid-svg-Ub0oybpGhsoW07Vy .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-Ub0oybpGhsoW07Vy .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-Ub0oybpGhsoW07Vy .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-Ub0oybpGhsoW07Vy .noteText,#mermaid-svg-Ub0oybpGhsoW07Vy .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-Ub0oybpGhsoW07Vy .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-Ub0oybpGhsoW07Vy .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-Ub0oybpGhsoW07Vy .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-Ub0oybpGhsoW07Vy .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .section{stroke:none;opacity:0.2}#mermaid-svg-Ub0oybpGhsoW07Vy .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-Ub0oybpGhsoW07Vy .section2{fill:#fff400}#mermaid-svg-Ub0oybpGhsoW07Vy .section1,#mermaid-svg-Ub0oybpGhsoW07Vy .section3{fill:#fff;opacity:0.2}#mermaid-svg-Ub0oybpGhsoW07Vy .sectionTitle0{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .sectionTitle1{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .sectionTitle2{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .sectionTitle3{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-Ub0oybpGhsoW07Vy .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .grid path{stroke-width:0}#mermaid-svg-Ub0oybpGhsoW07Vy .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-Ub0oybpGhsoW07Vy .task{stroke-width:2}#mermaid-svg-Ub0oybpGhsoW07Vy .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .taskText:not([font-size]){font-size:11px}#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-Ub0oybpGhsoW07Vy .task.clickable{cursor:pointer}#mermaid-svg-Ub0oybpGhsoW07Vy .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-Ub0oybpGhsoW07Vy .taskText0,#mermaid-svg-Ub0oybpGhsoW07Vy .taskText1,#mermaid-svg-Ub0oybpGhsoW07Vy .taskText2,#mermaid-svg-Ub0oybpGhsoW07Vy .taskText3{fill:#fff}#mermaid-svg-Ub0oybpGhsoW07Vy .task0,#mermaid-svg-Ub0oybpGhsoW07Vy .task1,#mermaid-svg-Ub0oybpGhsoW07Vy .task2,#mermaid-svg-Ub0oybpGhsoW07Vy .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutside0,#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutside2{fill:#000}#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutside1,#mermaid-svg-Ub0oybpGhsoW07Vy .taskTextOutside3{fill:#000}#mermaid-svg-Ub0oybpGhsoW07Vy .active0,#mermaid-svg-Ub0oybpGhsoW07Vy .active1,#mermaid-svg-Ub0oybpGhsoW07Vy .active2,#mermaid-svg-Ub0oybpGhsoW07Vy .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-Ub0oybpGhsoW07Vy .activeText0,#mermaid-svg-Ub0oybpGhsoW07Vy .activeText1,#mermaid-svg-Ub0oybpGhsoW07Vy .activeText2,#mermaid-svg-Ub0oybpGhsoW07Vy .activeText3{fill:#000 !important}#mermaid-svg-Ub0oybpGhsoW07Vy .done0,#mermaid-svg-Ub0oybpGhsoW07Vy .done1,#mermaid-svg-Ub0oybpGhsoW07Vy .done2,#mermaid-svg-Ub0oybpGhsoW07Vy .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-Ub0oybpGhsoW07Vy .doneText0,#mermaid-svg-Ub0oybpGhsoW07Vy .doneText1,#mermaid-svg-Ub0oybpGhsoW07Vy .doneText2,#mermaid-svg-Ub0oybpGhsoW07Vy .doneText3{fill:#000 !important}#mermaid-svg-Ub0oybpGhsoW07Vy .crit0,#mermaid-svg-Ub0oybpGhsoW07Vy .crit1,#mermaid-svg-Ub0oybpGhsoW07Vy .crit2,#mermaid-svg-Ub0oybpGhsoW07Vy .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-Ub0oybpGhsoW07Vy .activeCrit0,#mermaid-svg-Ub0oybpGhsoW07Vy .activeCrit1,#mermaid-svg-Ub0oybpGhsoW07Vy .activeCrit2,#mermaid-svg-Ub0oybpGhsoW07Vy .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-Ub0oybpGhsoW07Vy .doneCrit0,#mermaid-svg-Ub0oybpGhsoW07Vy .doneCrit1,#mermaid-svg-Ub0oybpGhsoW07Vy .doneCrit2,#mermaid-svg-Ub0oybpGhsoW07Vy .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-Ub0oybpGhsoW07Vy .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-Ub0oybpGhsoW07Vy .milestoneText{font-style:italic}#mermaid-svg-Ub0oybpGhsoW07Vy .doneCritText0,#mermaid-svg-Ub0oybpGhsoW07Vy .doneCritText1,#mermaid-svg-Ub0oybpGhsoW07Vy .doneCritText2,#mermaid-svg-Ub0oybpGhsoW07Vy .doneCritText3{fill:#000 !important}#mermaid-svg-Ub0oybpGhsoW07Vy .activeCritText0,#mermaid-svg-Ub0oybpGhsoW07Vy .activeCritText1,#mermaid-svg-Ub0oybpGhsoW07Vy .activeCritText2,#mermaid-svg-Ub0oybpGhsoW07Vy .activeCritText3{fill:#000 !important}#mermaid-svg-Ub0oybpGhsoW07Vy .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-Ub0oybpGhsoW07Vy g.classGroup text .title{font-weight:bolder}#mermaid-svg-Ub0oybpGhsoW07Vy g.clickable{cursor:pointer}#mermaid-svg-Ub0oybpGhsoW07Vy g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-Ub0oybpGhsoW07Vy g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-Ub0oybpGhsoW07Vy .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-Ub0oybpGhsoW07Vy .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-Ub0oybpGhsoW07Vy .dashed-line{stroke-dasharray:3}#mermaid-svg-Ub0oybpGhsoW07Vy #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy .commit-id,#mermaid-svg-Ub0oybpGhsoW07Vy .commit-msg,#mermaid-svg-Ub0oybpGhsoW07Vy .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-Ub0oybpGhsoW07Vy g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-Ub0oybpGhsoW07Vy g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-Ub0oybpGhsoW07Vy g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-Ub0oybpGhsoW07Vy .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-Ub0oybpGhsoW07Vy .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-Ub0oybpGhsoW07Vy .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-Ub0oybpGhsoW07Vy .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-Ub0oybpGhsoW07Vy .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-Ub0oybpGhsoW07Vy .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-Ub0oybpGhsoW07Vy .edgeLabel text{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Ub0oybpGhsoW07Vy .node circle.state-start{fill:black;stroke:black}#mermaid-svg-Ub0oybpGhsoW07Vy .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-Ub0oybpGhsoW07Vy #statediagram-barbEnd{fill:#9370db}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-state .divider{stroke:#9370db}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-Ub0oybpGhsoW07Vy .note-edge{stroke-dasharray:5}#mermaid-svg-Ub0oybpGhsoW07Vy .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-Ub0oybpGhsoW07Vy .error-icon{fill:#522}#mermaid-svg-Ub0oybpGhsoW07Vy .error-text{fill:#522;stroke:#522}#mermaid-svg-Ub0oybpGhsoW07Vy .edge-thickness-normal{stroke-width:2px}#mermaid-svg-Ub0oybpGhsoW07Vy .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-Ub0oybpGhsoW07Vy .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-Ub0oybpGhsoW07Vy .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-Ub0oybpGhsoW07Vy .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-Ub0oybpGhsoW07Vy .marker{fill:#333}#mermaid-svg-Ub0oybpGhsoW07Vy .marker.cross{stroke:#333}:root { --mermaid-font-family: "trebuchet ms", verdana, arial;}#mermaid-svg-Ub0oybpGhsoW07Vy {color: rgba(0, 0, 0, 0.75);font: ;}类成员成员变量attribute属性property成员方法实例变量类变量实例方法静态方法类方法

“实例变量”就是某个实例(或对象)个体特有的“数据”,例如学生的姓名、学号、性别等。
代码演示:

class Student(object):"""定义学生类"""def __init__(self, name, sex, student_id):self.name = name# 定义姓名实例变量self.sex = sex# 定义性别实例变量self.student_id = student_id# 定义学号实例变量student = Student('张三', 1, 1711010201)print('姓名:{0}'.format(student.name))
print('性别:{0}'.format('女'if student.sex == 0 else '男'))
print('学号:{0}'.format(student.student_id))

结果:

注意:代码def语句是构造方法,构造方法是用来创建和初始化实例变量的。构造方法中的self指向当前实例的引用。代码self.name是在创建和初始化实例变量name,其中self.name表示对象的name实例变量。student.name是访问name实例变量。

  • 类变量

“类变量”是所有实例(或对象)共有的变量。例如,学生的学费,假设每人的学费相同,那就可以在学生的类中设置一个类变量。
代码演示(上例代码重构):

class Student(object):"""定义学生类"""tuition = 4800# 类变量学费def __init__(self, name, sex, student_id):self.name = name# 定义姓名实例变量self.sex = sex# 定义性别实例变量self.student_id = student_id# 定义学号实例变量student = Student('张三', 1, 1711010201)print('姓名:{0}'.format(student.name))
print('性别:{0}'.format('女'if student.sex == 0 else '男'))
print('学号:{0}'.format(student.student_id))
print('学费:{0}'.format(Student.tuition))

结果:

注意:类变量在方法之外定义,访问通过“类名.类变量”的形式访问。切勿通过“实例名.类变量”的形式访问,不符合设计规范。也不要在类之外创建实例变量,他们无法通过类中的方法访问。

  • 构造方法

在前几例代码中有_init_()方法,该方法用来创建和初始化实例变量,这种方法就是“构造方法”。init()方法也属于魔法方法。
在此不做代码演示。
注意:定义时他的第一个参数是self,其后的参数才是用来初始化实例变量的,这些参数可以有默认值。调用构造方法是不需要传入self。

  • 实例方法

实例方法与实例变量一样都是某个实例(或对象)个体特有的。
方法是定义在类中的函数,而定义实例方法时他的第一个参数也应该是self,这个过程是将当前实例与该方法绑定起来,使该方法称为实例方法。

代码演示:

class Student(object):"""定义学生类"""tuition = 4800# 类变量学费def __init__(self, name, sex, student_id, weight):self.name = name# 定义姓名实例变量self.sex = sex# 定义性别实例变量self.student_id = student_id# 定义学号实例变量self.weight = weight# 定义体重实例变量def eat(self):self.weight += 0.8print('eat...')student = Student('张三', 1, 1711010201, 60)print('姓名:{0}'.format(student.name))
print('性别:{0}'.format('女'if student.sex == 0 else '男'))
print('学号:{0}'.format(student.student_id))
print('学费:{0}'.format(Student.tuition))
print('体重:{0}'.format(student.weight))
student.eat()
print('{0}体重:{1}'.format(student.name, student.weight))

结果:

注意:student.eat()语句就是调用实例方法

  • 类方法

“类方法”与“类变量”类似属于类,不属于个体实例的方法,类方法不需要与实例绑定,但需要与类绑定,定义时他的第一个参数是类的type实例。type是描述Python数据类型的类,Python中所有数据类型都是type的一个实例。
代码演示:

class Student(object):"""定义学生类"""tuition = 4800# 类变量学费def __init__(self, name, sex, student_id, weight):self.name = name# 定义姓名实例变量self.sex = sex# 定义性别实例变量self.student_id = student_id# 定义学号实例变量self.weight = weight# 定义体重实例变量def eat(self):self.weight += 0.8print('eat...')# 学费与重修费之和@classmethoddef tuition_add(cls, repair_fee):return cls.tuition + repair_feestudent = Student('张三', 1, 1711010201, 60)print('姓名:{0}'.format(student.name))
print('性别:{0}'.format('女'if student.sex == 0 else '男'))
print('学号:{0}'.format(student.student_id))
print('学费:{0}'.format(Student.tuition))
print('体重:{0}'.format(student.weight))
student.eat()
print('{0}体重:{1}'.format(student.name, student.weight))
print('学费与重修费总和:{0}'.format(Student.tuition_add(400)))

结果:

注意:定义类方法的两个关键:
一、方法第一个参数是cls是type类型,是当前Student类型的实例;
二、方法使用装饰器@classmethod声明该方法是类方法。
类方法使用:
类方法可以访问类变量和其他类方法,但不可访问其他实例方法和实例变量;
类方法调用采用“类名.类方法”形式调用。可以通过实例调用,但不符合规矩。

  • 静态方法

如果定义的方法既不想与实例绑定,又不想与类绑定,只是想把类作为他的命名空间,那么可以定义静态方法。
代码演示(上述代码重构):

class Student(object):"""定义学生类"""tuition = 4800# 类变量学费def __init__(self, name, sex, student_id, weight):self.name = name# 定义姓名实例变量self.sex = sex# 定义性别实例变量self.student_id = student_id# 定义学号实例变量self.weight = weight# 定义体重实例变量def eat(self):self.weight += 0.8print('eat...')# 学费与重修费之和# 类方法@classmethoddef tuition_add(cls, repair_fee):return cls.tuition + repair_fee# 静态方法@staticmethoddef tuition_with(repair_fee):return Student.tuition_add(repair_fee)student = Student('张三', 1, 1711010201, 60)print('姓名:{0}'.format(student.name))
print('性别:{0}'.format('女'if student.sex == 0 else '男'))
print('学号:{0}'.format(student.student_id))
print('学费:{0}'.format(Student.tuition))
print('体重:{0}'.format(student.weight))
student.eat()
print('{0}体重:{1}'.format(student.name, student.weight))
print('学费与重修费总和:{0}'.format(Student.tuition_add(400)))
print('学费与重修费总和:{0}'.format(Student.tuition_with(400)))

结果:

注意:@staticmethod装饰器,声明方法是静态方法,方法参数不指定self和cls。
调用静态方法与调用类方法相似都通过类名实现,也可以通过实例调用,但不符合规范。
类方法与静态方法在很多场景是类似的,只是在定义时有一些区别。类方法需要绑定类,静态方法不需要绑定类,静态方法与类的耦合度更加松散。
在类中定义静态方法只是为了提供一个基于类名的命名空间。

欢迎参考学习,有错请指证,喜欢的请关注本人博客,不定期更新学习心得,学习笔记。

Python基础学习——面向对象编程(第一讲:面向对象概述、面向对象三个基本特征(封装性、继承性、多态性)、类和对象(定义类、创建和使用对象、实例变量、类变量、构造方法、实例方法、类方法、静态方法))相关推荐

  1. python面向对象编程98讲_谈面向对象的编程(Python)

    (注:本文部分内容摘自互联网,由于作者水平有限,不足之处,还望留言指正.) 今天中秋节,也没什么特别的,寻常日子依旧. 谈谈面向对象吧,什么叫面向对象? 那么问题来了,你有对象吗? 嗯,,,那我可以做 ...

  2. Java基础学习第十二讲:Java面向对象---抽象类和接口

    Java面向对象-抽象类和接口 一.抽象类 抽象的定义: 我们在日常生活中,经常通过总结一些事物的共性来对事物进行分类,这种共性可能是一些相同的属性,也可能是一些相同的动作.通过总结,我们能够清晰的划 ...

  3. 类方法的实例python_Python Class 的实例方法/类方法/静态方法

    实例方法.类方法.静态方法 class MyClass(object): class_name = "MyClass" # 类属性, 三种方法都能调用 def __init__(s ...

  4. python基础学习笔记12:Python面向对象编程

    面向对象编程思想 1.什么是面向过程 传统的面向过程的编程思想总结起来就八个字--自顶向下,逐步细化! 将要实现的功能描述为一个从开始到结束按部就班的连续的"步骤" 依次逐步完成这 ...

  5. 8.Python基础学习笔记day8-正则表达式、网络编程、进程与线程

    8.Python基础学习笔记day8-正则表达式.网络编程.进程与线程 一.正则表达式 ''' 1. [1,2,3,4]中任意取3个元素排列: A43 = 4x3x2 = 24itertools.pe ...

  6. 高阶函数||编程范式: 命令式编程/声明式编程 || 编程范式: 面向对象编程(第一公民:对象)/函数式编程(第一公民:函数)

    编程范式: 命令式编程/声明式编程 编程范式: 面向对象编程(第一公民:对象)/函数式编程(第一公民:函数) 高阶函数 filter/map/reduce filter中的回调函数有一个要求: 必须返 ...

  7. 面向对象技术第一讲 多态性

    面向对象技术第一讲  多态性 一﹑什么是多态?为什么要支持多态? 多态是一种普遍存在的现象,如water的三种形态:冰﹑水﹑汽,又如算术运算1+1, 1+0.5, 1/2+0.5等. 多态性用一句经典 ...

  8. 从零开始学习VIO笔记 --- 第一讲:基础知识(四元数,李代数)

    从零开始学习VIO笔记 --- 第一讲:基础知识(四元数,李代数) 一. 向量的内积与外积 二. 旋转与平移 2.1 旋转表示 --- 旋转矩阵R 2.2 平移向量 2.3 变换矩阵T与齐次坐标 2. ...

  9. 面向对象技术第一讲 多态性(原创)

    面向对象技术第一讲  多态性   一﹑什么是多态?为什么要支持多态? 多态是一种普遍存在的现象,如water的三种形态:冰﹑水﹑汽,又如算术运算1+1, 1+0.5, 1/2+0.5等. 多态性用一句 ...

最新文章

  1. Android深度探索第四章
  2. ASP.NET服务器应用程序不可用
  3. 数学中不可能实现的图形
  4. cf1207解题报告
  5. 相机添加多张图片css布局
  6. 语义化版本控制规范(SemVer)
  7. C++有符号和无符号数的转换
  8. Linux 动态链接和静态链接简析(库名与库文件名)
  9. Mac在github中管理自己的代码(入门篇)
  10. epoll监听文件_epoll
  11. uboot调试过程:用来调试phy不通的过程(am3352)
  12. draw.io箭头设置虚线
  13. iis 安装完ssl 证书谷歌浏览器还是提示不安全的解决方法
  14. C++中如何使输出对齐
  15. PowerDesigner 16逆向工程,MySQL数据库的生成PDM物理数据模型文件
  16. 【OpenCV】 全景拼接——多张图像拼接
  17. 用Raphael在网页中画圆环进度条(简化版)
  18. KITTI如何submit自己的模型效果
  19. android 7.1快捷方式App Shortcuts
  20. 计算机毕业设计:基于微信小程序的校园求职系统

热门文章

  1. 费米估算类问题-解决方法
  2. 关于浏览器查看网页中文乱码问题
  3. Unity 游戏皇家消消乐Android版
  4. 小红书10万粉算大号么?快速涨粉实用技巧
  5. ADRC线性跟踪微分器(ST+SCL语言)
  6. activiti的使用
  7. 数字政府智慧政务一网通办解决方案2022(ppt可编辑)
  8. 程序员必须掌握的100个英语单词
  9. 产品卖点怎么提炼?研究搜索词能帮助卖点提炼
  10. Starfall|“造轮子”是一种乐趣吗?