Python/Article/python9/2.md

118 lines
3.1 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、定义类 ##
类定义语法格式如下:
```python
class ClassName:
<statement-1>
.
.
.
<statement-N>
```
一个类也是由属性和方法组成的,有些时候我们定义类的时候需要设置类的属性,因此这就需要构造函
类的构造函数如下:
```python
def __init__(self,[...):
```
类定义了 __init__() 方法的话,类的实例化操作会自动调用 __init__() 方法。
那么如构造函数相对应的是析构函数,理所当然,一个类创建的时候我们可以用过构造函数设置属性,那么当一个类销毁的时候,就会调用析构函数。
析构函数语法如下:
```python
def __del__(self,[...):
```
仔细观察的童鞋都会发现,类的方法与普通的函数有一个特别的区别,它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。
那么这个 self 代表什么呢?
我们可以看下实例,通过实例来找出答案:
```python
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
```
观察输出的结果:
![Python self](http://upload-images.jianshu.io/upload_images/2136918-66d29b081ad5510b?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
从执行结果可以很明显的看出self 代表的是类的实例,输出的是当前对象的地址,而 `self.__class__` 则指向类。
当然 self 不是 python 关键字,也就是说我们把他换成其他的字符也是可以正常执行的。只不过我们习惯使用 self
## 2、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))
```
仔细观察输出的结果对比一下就能观察出来注意喔Pyhton3 中输出的结果是一模一样的因为Python3 中没有新式类旧式类的问题。