Python/Article/PythonBasis/python8/2.md

84 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 二、类的定义和调用 #
## 1、怎么理解类 ##
类是什么?
个人认为理解类,最简单的方式就是:类是一个变量和函数的集合。
可以看下下面的这张图。
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-08-034102.png)
这张图很好的诠释了类,就是把变量和函数包装在一起。
当然我们包装也不是毫无目的的包装,我们会把同性质的包装在一个类里,这样就方便我们重复使用。
所以学到现在,你会发现很多编程的设计,都是为了我们能偷懒,重复使用。
## 2、怎么定义类 ##
知道了类是什么样子的,我们接下来就要学习怎么去定义类了。
类定义语法格式如下:
```python
class ClassName():
<statement-1>
.
.
.
<statement-N>
```
可以看到,我们是用 `class` 语句来自定义一个类的,其实这就好比我们是用 `def` 语句来定义一个函数一样。
竟然说类是变量和方法的集合包,那么我们来创建一个类。
```python
class ClassA():
var1 = 100
var2 = 0.01
var3 = '两点水'
def fun1():
print('我是 fun1')
def fun2():
print('我是 fun1')
def fun3():
print('我是 fun1')
```
你看,上面我们就定义了一个类,类名叫做 `ClassA` , 类里面的变量我们称之为属性,那么就是这个类里面有 3 个属性,分别是 `var1` , `var2``var3` 。除此之外,类里面还有 3 个类方法 `fun1()` , `fun2()``fun3()`
## 3、怎么调用类属性和类方法 ##
我们定义了类之后,那么我们怎么调用类里面的属性和方法呢?
直接看下图:
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-08-083155.png)
这里就不文字解释了(注:做图也不容易啊,只有写过技术文章才知道,这系列文章,多耗时)
好了,知道怎么调用之后,我们尝试一下:
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-08-085918.png)