在学习程序语言的过程中,应该都有听过物件导向程序设计(Object-oriented programming,缩写:OOP),在 Python 也有相似的用法。它是使用物件(Object)的概念去开发,能够提高软件的扩充性、维护性、跟重复使用率,在 Python 中要使用物件导向就需要熟悉关於类别(Class)及物件(Object)的相关知识。
相关的知识包含了五种,如下
在开始之前,先来看看程序码吧!
# 人类类别
class human:
# 建构式
def __init__(self, name, height):
self.name = name # 名字属性
self.height = height # 身高属性
# 方法 Method
def say_hi(self):
print("Hello, I am", self.name, "and", self.height, "tall.")
# 物件
Taiwanese = human()
接下来会分别介绍各个部分。
可以想像是物件(Object)的组成条件,用来定义这个物件的属性 Attribute 及方法 Method,像是一个台湾人它有名字还有身高(属性 Attribute),并且他会可能会跟人打招呼(方法Method)。定义类别(Class)的语法如下
class classname:
statement
类别名称习惯使用 Pascal 命名法。
每个单字字首大写,不得使用空白或底线分隔单字
透过类别 Class 实际建立出来的东西,像是一个台湾人(Taiwanese)。建立物件的语法如下
object_name = classname()
范例
Taiwanese = human()
isinstace()
:用来判断类别 Class 与物件 Object 的关系
# 人类类别
class human:
pass
# 动物类别
class animal:
pass
# 建立 human 类别的物件
Taiwanese = human()
print(isinstance(Taiwanese, human)) # True
print(isinstance(Taiwanese, animal)) # False
剩下的部份我们明天再来继续介绍!
待续...
<<: 成为工具人应有的工具包-22 OpenedFilesView
记得第一次使用到 css 的 animation 跟 transform 系列效果 做了很多厉害的...
前言 前面介绍的工具都是命令行工具,但存在着一些的不便 分析数据透过终端机文字的方式显示,不够直觉 ...
今天先来进行呼叫永丰API 串接永丰API 按照范例测试,主要针对建立订单进行实作,查询订单等API...
什麽是 object-fit object-fit 是一个 CSS 属性,用於决定一个可替换 res...
Traces - 观察应用程序的效能瓶颈 系列文章 (1/6) - Elastic APM 基本介绍...