Python/Article/PythonBasis/python8/6.md

147 lines
4.3 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-09-071102.png)
当代码在执行 `a = ClassA()` 的语句时,就自动调用了 `__init__(self)` 函数。
**而这个 `__init__(self)` 函数就是初始化函数,也叫构造函数。**
初始化函数的写法是固定的格式:中间是 `init`,意思是初始化,然后前后都要有【两个下划线】,然后 `__init__()` 的括号中,第一个参数一定要写上 `self`,不然会报错。
构造函数(初始化函数)格式如下:
```python
def __init__(self,[...):
```
初始化函数一样可以传递参数的,例如:
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-09-073421.png)
## 2、析构函数 ##
竟然一个在创建的时候,会调用构造函数,那么理所当然,这个当一个类销毁的时候,就会调用析构函数。
析构函数语法如下:
```python
def __del__(self,[...):
```
看下具体的示例:
![](http://twowaterimage.oss-cn-beijing.aliyuncs.com/2019-10-09-084417.png)
## 3、Python 定义类的历史遗留问题 ##
Python 在版本的迭代中,有一个关于类的历史遗留问题,就是新式类和旧式类的问题,具体先看以下的代码:
```python
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 旧式类
class OldClass:
pass
# 新式类
class NewClass(object):
pass
```
可以看到,这里使用了两者中不同的方式定义类,可以看到最大的不同就是,新式类继承了`object` 类,在 Python2 中,我们定义类的时候最好定义新式类,当然在 Python3 中不存在这个问题了,因为 Python3 中所有类都是新式类。
那么新式类和旧式类有什么区别呢?
运行下下面的那段代码:
```python
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 旧式类
class OldClass:
def __init__(self, account, name):
self.account = account
self.name = name
# 新式类
class NewClass(object):
def __init__(self, account, name):
self.account = account
self.name = name
if __name__ == '__main__':
old_class = OldClass(111111, 'OldClass')
print(old_class)
print(type(old_class))
print(dir(old_class))
print('\n')
new_class = NewClass(222222, 'NewClass')
print(new_class)
print(type(new_class))
print(dir(new_class))
```
这是 python 2.7 运行的结果:
```
/Users/twowater/dev/python/test/venv/bin/python /Users/twowater/dev/python/test/com/twowater/test.py
<__main__.OldClass instance at 0x109a50560>
<type 'instance'>
['__doc__', '__init__', '__module__', 'account', 'name']
<__main__.NewClass object at 0x109a4b150>
<class '__main__.NewClass'>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'account', 'name']
Process finished with exit code 0
```
这是 Python 3.6 运行的结果:
```
/usr/local/bin/python3.6 /Users/twowater/dev/python/test/com/twowater/test.py
<__main__.OldClass object at 0x1038ba630>
<class '__main__.OldClass'>
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'account', 'name']
<__main__.NewClass object at 0x103e3c9e8>
<class '__main__.NewClass'>
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'account', 'name']
Process finished with exit code 0
```
仔细观察输出的结果对比一下就能观察出来注意喔Pyhton3 中输出的结果是一模一样的因为Python3 中没有新式类旧式类的问题。