mirror of
https://github.com/apachecn/ailearning.git
synced 2026-02-10 05:45:40 +08:00
108 lines
1.4 KiB
Markdown
108 lines
1.4 KiB
Markdown
# 简介
|
||
|
||
## 属性 attributes
|
||
|
||
属性是与对象绑定的一组数据,可以只读,只写,或者读写,使用时不加括号,例如:
|
||
|
||
In [1]:
|
||
|
||
```py
|
||
f = file("new_file", 'w')
|
||
|
||
```
|
||
|
||
显示模式属性:
|
||
|
||
In [2]:
|
||
|
||
```py
|
||
f.mode
|
||
|
||
```
|
||
|
||
Out[2]:
|
||
|
||
```py
|
||
'w'
|
||
```
|
||
|
||
是否关闭:
|
||
|
||
In [3]:
|
||
|
||
```py
|
||
f.closed
|
||
|
||
```
|
||
|
||
Out[3]:
|
||
|
||
```py
|
||
False
|
||
```
|
||
|
||
`mode` 是只读属性,所以这样会报错:
|
||
|
||
In [4]:
|
||
|
||
```py
|
||
f.mode = 'r'
|
||
|
||
```
|
||
|
||
```py
|
||
---------------------------------------------------------------------------
|
||
TypeError Traceback (most recent call last)
|
||
<ipython-input-4-d9757d46f855> in <module>()
|
||
----> 1 f.mode = 'r'
|
||
|
||
TypeError: readonly attribute
|
||
```
|
||
|
||
获取属性不需要加括号:
|
||
|
||
In [5]:
|
||
|
||
```py
|
||
f.mode()
|
||
|
||
```
|
||
|
||
```py
|
||
---------------------------------------------------------------------------
|
||
TypeError Traceback (most recent call last)
|
||
<ipython-input-5-6b67c2ae8f67> in <module>()
|
||
----> 1 f.mode()
|
||
|
||
TypeError: 'str' object is not callable
|
||
```
|
||
|
||
## 方法 method
|
||
|
||
方法是与属性绑定的一组函数,需要使用括号,作用于对象本身:
|
||
|
||
In [6]:
|
||
|
||
```py
|
||
f.write('Hi.\n')
|
||
f.seek(0)
|
||
f.write('Hola!\n')
|
||
f.close()
|
||
|
||
```
|
||
|
||
In [7]:
|
||
|
||
```py
|
||
!rm new_file
|
||
|
||
```
|
||
|
||
## 使用 OPP 的原因
|
||
|
||
* 构建自己的类型来模拟真实世界的对象
|
||
* 处理抽象对象
|
||
* 容易复用和扩展
|
||
* 理解其他 OPP 代码
|
||
* GUI 通常使用 OPP 规则编写
|
||
* ... |