本节内容:
- 面向对象高级语法部分异常处理异常处理异常处理
- 经典类vs新式类
- 静态方法、类方法、属性方法
- 类的特殊方法
- 反射
- 异常处理
- 作业:开发一个支持多用户在线的FTP程序
面向对象高级语法部分
1、经典类vs新式类
参考:http://www.cnblogs.com/ant-colonies/p/6719724.html
2、实例方法、静态方法、类方法、属性方法
2.1 实例方法
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5 def __init__(self, name):
6 self.name = name
7 print('name = %s' %self.name)
8 def sleep(self):
9 print('going to sleep...')
10
11 print(Dog.sleep)
12 '''<unbound method Dog.sleep>'''
13
14 Dog.sleep()
15 '''
16 Traceback (most recent call last):
17 File "py_instance.py", line 12, in <module>
18 Dog.sleep()
19 TypeError: unbound method sleep() must be called with Dog instance as first argument (got nothing instead)
20 '''
21 '''
22 Dog.sleep是未绑定的方法
23 必须以类Dog的实例对象作为未绑定的方法sleep()的第一参数,sleep方法才能被调用
24 '''
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5 def __init__(self, name):
6 self.name = name
7 print('self.name = %s' %self.name)
8 print('self : %s' %type(self))
9 def sleep():
10 print('going to sleep...')
11
12 d = Dog('Tim')
13 print(d.sleep)
14 d.sleep()
15
16 '''
17 一旦实例化, __init__方法立即执行
18 self.name = Tim
19
20 self是一个类对象
21 self : <class '__main__.Dog'>
22
23 通过实例化,使得Dog.sleep实现绑定
24 <bound method Dog.sleep of <__main__.Dog object at 0x7ffa7deeedd0>>
25
26 d.sleep()将实例对象作为第一参数传给sleep方法,但是sleep方法无形参
27 Traceback (most recent call last):
28 File "py_instance.py", line 14, in <module>
29 d.sleep()
30 TypeError: sleep() takes no arguments (1 given)
31 '''
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5 def __init__(self, name):
6 self.name = name
7 print('self.name = %s' %self.name)
8 print('self : %s' %type(self))
9 def sleep(name):
10 print('%s going to sleep...' %name)
11 print('%s going to sleep...' %name.name)
12
13 d = Dog('Tim')
14 print(d.sleep)
15 d.sleep()
16
17 '''
18 self.name = Tim
19 self : <class '__main__.Dog'>
20
21 实例对象的内存地址
22 <bound method Dog.sleep of <__main__.Dog object at 0x7fb3f2605dd0>>
23
24 诶,实例对象传给了name
25 <__main__.Dog object at 0x7f98f2176ed0> going to sleep...
26 Tim going to sleep...
27 '''
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5 def __init__(self, name):
6 self.name = name
7 print('self.name = %s' %self.name)
8 print('self : %s' %type(self))
9 def sleep(self):
10 print('%s going to sleep...' %self.name)
11
12 d = Dog('Tim')
13 print(d.sleep)
14 d.sleep()
15
16 '''
17 self.name = Tim
18 self : <class '__main__.Dog'>
19 <bound method Dog.sleep of <__main__.Dog object at 0x7f627e678e90>>
20
21 python中实例方法中的第一参数为实例对象本身, 默认self作为第一形参
22 Tim going to sleep...
23 '''
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5 def __init__(self, name):
6 self.name = name
7 print('self.name = %s' %self.name)
8 print('self : %s' %type(self))
9 def sleep(self):
10 print('%s going to sleep...' %self.name)
11
12 d = Dog('Tim')
13 f = Dog('Tim')
14 print(d == f)
15 print(d.sleep is f.sleep())
16
17 '''
18 self.name = Tim
19 self : <class '__main__.Dog'>
20 self.name = Tim
21 self : <class '__main__.Dog'>
22
23 实例化出两个对象
24 False
25 Tim going to sleep...
26 False
27 '''
2.2 静态方法
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5
6 stat = 'awake'
7
8 def __init__(self):
9 pass
10 #print('self.name = %s' %self.name)
11 #print('self : %s' %type(self))
12
13 @staticmethod
14 def sleep():
15 print('going to sleep...')
16
17 print(Dog.stat)
18 print(Dog().stat)
19 print(type(Dog.stat))
20 print(type(Dog().stat))
21 Dog.sleep()
22 Dog().sleep()
23 print(Dog.sleep)
24 print(Dog().sleep)
25 print(Dog.sleep is Dog.sleep)
26 print(Dog().sleep is Dog.sleep)
27
28 '''
29 静态方法与类变量性质相似,逻辑上隶属于类,其实独立于类,不受类的影响
30 awake
31 awake
32 <type 'str'>
33 <type 'str'>
34 going to sleep...
35 going to sleep...
36 <function sleep at 0x7f3f3fb238c0>
37 <function sleep at 0x7f3f3fb238c0>
38 True
39 True
40 '''
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5
6 def __init__(self, name):
7 self.name = name
8 print('self.name = %s' %self.name)
9
10 @staticmethod
11 def sleep(self):
12 static_var = 'STATIC'
13 print('%s is going to sleep...%s' %(self, static_var))
14
15
16 Dog('Tim').sleep('Jerry')
17 print(Dog.sleep('Jerff').static_var)
18 Dog.sleep('Jerff').static_var = 'Here'
19 print(Dog.sleep('Jerff').static_var)
20
21 """
22 静态方法相当于类变量,是一块代码块逻辑,不存在静态方法内部的调用问题
23 self.name = Tim
24 Jerry is going to sleep...STATIC
25 Jerff is going to sleep...STATIC
26 Traceback (most recent call last):
27 File "py_instance.py", line 17, in <module>
28 print(Dog.sleep('Jerff').static_var)
29 AttributeError: 'NoneType' object has no attribute 'static_var'
30 """
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5
6 def __init__(self, name):
7 self.name = name
8 print('self.name = %s' %self.name)
9
10 @staticmethod
11 def sleep(self):
12 print('%s is going to sleep...' %self)
13
14
15 Dog('Tim').sleep('Jerry')
16 print(Dog('Tim').sleep('Jerry') is Dog.sleep('Jerff'))
17
18
19 ''' 再次证明类与静态方法无关
20 self.name = Tim
21 Jerry is going to sleep...
22 self.name = Tim
23 Jerry is going to sleep...
24 Jerff is going to sleep...
25 True
26 '''
1 # -*- coding:utf-8 -*-
2 #
3
4 class Dog(object):
5 class_var = 'Hrrrrrrrrrrrrr......'
6
7 def __init__(self, name):
8 self.name = name
9 print('self.name = %s' %self.name)
10
11 @staticmethod
12 def sleep(self):
13 print('%s is going to sleep...' %self)
14
15
16 class Animal(Dog):
17 def sleep(self):
18 print('%s is here...' %self.name)
19 print('static method can be overrided by subclass...')
20
21 if __name__ == '__main__':
22 Dog('Tim').sleep('Jerry')
23 print(Dog('Tim').sleep('Jerry') is Dog.sleep('Jerff'))
24 print(Dog.class_var)
25 Dog.class_var = 'changed......'
26 print(Dog.class_var)
27 Animal('Jack').sleep()
28
29 ''' 静态方法可以在子类中被重写
30 self.name = Tim
31 Jerry is going to sleep...
32 self.name = Tim
33 Jerry is going to sleep...
34 Jerff is going to sleep...
35 True
36 Hrrrrrrrrrrrrr......
37 changed......
38 self.name = Jack
39 Jack is here...
40 static method can be overrided by subclass...
41 '''
由以上两例可知:
静态方法仅在逻辑上隶属于类,与类变量性质相当;
静态方法与类变量一样,执行时只在代码区生成一份,类或多个类实例共享同一个静态方法,相较于实例方法,每生成一个实例,就必须生成一个对象,静态方法更加高效,节约资源;
静态方法在子类中可被重写,且重写的方法不一定是静态方法。
2.3 类方法
1 # -*- coding:utf-8 -*-
2 #
3 class Dog(object):
4
5 def __init__(self, name):
6 self.name = name
7 print('self.name = %s' %self.name)
8
9 @classmethod
10 def sleep():
11 print('%s is going to sleep...' %self)
12
13 print(Dog.sleep)
14 Dog.sleep()
15
16 '''
17 与实例方法不一样,实例方法的绑定方法是Dog.sleep,类方法绑定的是type.sleep
18 <bound method type.sleep of <class '__main__.Dog'>>
19
20 类方法默认出入了一个类对象
21 Traceback (most recent call last):
22 File "py_instance.py", line 15, in <module>
23 Dog.sleep()
24 TypeError: sleep() takes no arguments (1 given)
25 '''
1 # -*- coding:utf-8 -*-
2 #
3 class Dog(object):
4
5 def __init__(self, name):
6 self.name = name
7 print('self.name = %s' %self.name)
8
9 @classmethod
10 def sleep(name):
11 print('%s is going to sleep...' %name)
12
13 print(Dog.sleep)
14 Dog.sleep()
15
16 ''' 类对象默认作为第一参数传入到类方法中
17 <bound method type.sleep of <class '__main__.Dog'>>
18 <class '__main__.Dog'> is going to sleep...
19 '''
1 # -*- coding:utf-8 -*-
2 #
3 class Dog(object):
4
5 name = 'Here'
6
7 def __init__(self, name):
8 self.name = name
9 # print('self.name = %s' %self.name)
10 # print('self = ' %type(self))
11
12 @staticmethod
13 def talk():
14 return 'Animals and me'
15
16 @classmethod
17 def sleep(cls):
18 print('%s is going to sleep...' %type(cls))
19 print('%s is going to sleep...' %cls.name)
20 print('%s are talking to each other...' %cls.talk())
21
22 print(Dog.sleep)
23 print(Dog.sleep is Dog.sleep)
24 Dog('Tim').sleep()
25
26 ''' 类方法对类变量和静态方法的调用
27 <bound method type.sleep of <class '__main__.Dog'>>
28 False
29 <type 'type'> is going to sleep...
30 Here is going to sleep...
31 Animals and me are talking to each other...
32 '''
由上面的例子可知:
类方法的优点参考:http://www.cnblogs.com/ant-colonies/p/6736567.html
2.4 属性方法
属性方法的作用就是通过@property把一个方法变成一个静态属性。
class Dog(object):
def __init__(self,name):
self.name = name
@property
def eat(self):
print(" %s is eating" %self.name)
d = Dog("ChenRonghua")
d.eat()
调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了。
Tim is eating
Traceback (most recent call last):
File "py_11.py", line 12, in <module>
d.eat()
TypeError: 'NoneType' object is not callable
正确的调用如下:
d = Dog("ChenRonghua")
d.eat
输出
ChenRonghua is eating
好吧,把一个方法变成静态属性有什么卵用呢?既然想要静态变量,那直接定义成一个静态变量不就得了么?well, 以后你会需到很多场景是不能简单通过 定义 静态属性来实现的, 比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:
1. 连接航空公司API查询
2. 对查询结果进行解析
3. 返回结果给你的用户
因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以,明白 了么?
1 # -*- coding:utf-8 -*-
2 #
3 class Flight(object):
4 def __init__(self, name):
5 self.flight_name = name
6 def checking_status(self):
7 print('checking flight %s status' %self.flight_name)
8 return 1
9
10 @property
11 def flight_status(self):
12 status = self.checking_status()
13 if status == 0:
14 print('flight got canceled...')
15 elif status == 1:
16 print('flight has arrived...')
17 elif status == 2:
18 print('flight has departured already...')
19 else:
20 print('cannot confirm the flight status, check it latter...')
21
22 f = Flight('CA980')
23 f.flight_status
24
25 '''
26 checking flight CA980 status
27 flight has arrived...
28 '''
cool , 那现在我只能查询航班状态, 既然这个flight_status已经是个属性了, 那我能否给它赋值呢?试试吧
f = Flight("CA980")
f.flight_status
f.flight_status = 2
输出, 说不能更改这个属性,我擦。。。。,怎么办怎么办。。。
checking flight CA980 status
flight has arrived...
[root@ant-colonies tmp]# python py_flight.py
checking flight CA980 status
flight has arrived...
Traceback (most recent call last):
File "py_flight.py", line 24, in <module>
f.flight_status = 2
AttributeError: can't set attribute
当然可以改, 不过需要通过@proerty.setter装饰器再装饰一下,此时 你需要写一个新方法, 对这个flight_status进行更改。
1 # -*- coding:utf-8 -*-
2 #
3 class Flight(object):
4 def __init__(self, name):
5 self.flight_name = name
6 def checking_status(self):
7 print('checking flight %s status' %self.flight_name)
8 return 1
9
10 @property
11 def flight_status(self):
12 status = self.checking_status()
13 if status == 0:
14 print('flight got canceled...')
15 elif status == 1:
16 print('flight has arrived...')
17 elif status == 2:
18 print('flight has departured already...')
19 else:
20 print('cannot confirm the flight status, check it latter...')
21
22 @flight_status.setter # modify
23 def flight_status(self, status):
24 status_dic = {
25 0 : 'canceled',
26 1 : 'arrived',
27 2 : 'departured'
28 }
29 print('