1、python特殊函数:
以 __ 开头且以 __ 结尾。
xxxxxxxxxx2
1
2、__getattr__ 和 __setattr__
__getattr__:拦截点号运算。当对未定义的属性名称和实例进行点号运算时,就会用属性名作为字符串调用这个方法。如果继承树可以找到该属性,则不调用此方法。
class empty:
def__getattr__(self, attrname):
if attrname =="age":
return 40;
else:
raise AttributeError, attrname
x = empty();
print(x.age) #40
print(x.name) #error text omitted.....AttributeError, name xxxxxxxxxx1
class empty:2
def__getattr__(self, attrname):3
if attrname =="age": 4
return 40;5
else:6
raise AttributeError, attrname7
8
x = empty();9
print(x.age) #40 10
print(x.name) #error text omitted.....AttributeError, name __setattr__:会拦截所有属性的的赋值语句。如果定义了这个方法,self.arrt = value 就会变成self,__setattr__("attr", value).这个需要注意。当在__setattr__方法内对属性进行赋值是,不可使用self.attr = value,因为他会再次调用self,__setattr__("attr", value),则会形成无穷递归循环,最后导致堆栈溢出异常。应该通过对属性字典做索引运算来赋值任何实例属性,也就是使用self.__dict__[‘name‘] = value.
# Python实现属性私有化的首选方式:
class PrivateExc(Exception):
pass
class Privacy:
def__setattr__(self, attrname, value):
if attrname inself.privates:
raisePrivateExc(attrname, self)
else:
self.__dict__[attrname]= value
classTest1(Privacy):
privates= ["age"]
classTest2(Privacy):
privates= ["name","age"]
def__init__(self):
self.__dict__["name"]= "sun"
x =Test1()
y =Test2()
x.name = "Tom" #执行成功
x.age =20 #执行失败,产生异常,该属性在privates列表内
y.name = "Mike" #执行失败,产生异常,该属性在privates列表内
y.age =20 #执行成功 xxxxxxxxxx1
25
1
# Python实现属性私有化的首选方式:2
class PrivateExc(Exception): 3
pass 4
5
class Privacy: 6
def__setattr__(self, attrname, value): 7
if attrname inself.privates: 8
raisePrivateExc(attrname, self) 9
else: 10
self.__dict__[attrname]= value 11
12
classTest1(Privacy): 13
privates= ["age"] 14
15
classTest2(Privacy): 16
privates= ["name","age"] 17
def__init__(self): 18
self.__dict__["name"]= "sun" 19
20
x =Test1() 21
y =Test2() 22
x.name = "Tom" #执行成功 23
x.age =20 #执行失败,产生异常,该属性在privates列表内 24
y.name = "Mike" #执行失败,产生异常,该属性在privates列表内 25
y.age =20 #执行成功 class User():
def __init__(self, username, password):
self._username = username
self._password = password
@property
def username(self):
return self._username
@username.setter
def username(self, username):
self._username = username
boy = User("name","pass");
print(boy.username());x
10
1
class User(): 2
def __init__(self, username, password):3
self._username = username4
self._password = password5
6
7
def username(self):8
return self._username9
10
.setter11
def username(self, username):12
self._username = username13
14
boy = User("name","pass");15
print(boy.username());4、上下文管理器:
with... as... 代码块
当越界后会有处理
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = ‘Alpha_Meng‘
#---------------------------------------
with open("test.txt","w") as f:
print(f.closed);
f.write("hello word");
print(f.closed); #此处不需要关闭文件,上下文管理器会自动关闭xxxxxxxxxx1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
__author__ = ‘Alpha_Meng‘5
6
#---------------------------------------7
with open("test.txt","w") as f:8
print(f.closed);9
f.write("hello word");10
print(f.closed); #此处不需要关闭文件,上下文管理器会自动关闭任何实现了 __enter__() 和 __exit__() 方法都可以做上下文管理。
所以自定义:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = ‘Alpha_Meng‘
class User(object):
def __init__(self, username, password):
self._username = username
self._password = password
@property
def username(self):
return self._username
@username.setter
def username(self, username):
self._username = username
@property
def password(self):
return self._password
@password.setter
def password(self, password):
self._password = password
def __enter__(self):
print(‘auto do something before statements body of with executed‘)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(‘auto do something after statements body of with executed: ‘ + self._username);
if __name__ == ‘__main__‘:
boy = User(‘shouke‘, ‘shouke2014‘)
print(boy.password)
with User(‘shouke‘, ‘2014‘) as user:
print(user.password)
print(‘---------end-----------‘)
print(user.password)
xxxxxxxxxx43
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
__author__ = ‘Alpha_Meng‘5
6
7
class User(object):8
def __init__(self, username, password):9
self._username = username10
self._password = password11
12
13
14
def username(self):15
return self._username16
17
.setter18
def username(self, username):19
self._username = username20
21
22
def password(self):23
return self._password24
25
.setter26
def password(self, password):27
self._password = password28
29
def __enter__(self):30
print(‘auto do something before statements body of with executed‘)31
return self32
33
def __exit__(self, exc_type, exc_val, exc_tb):34
print(‘auto do something after statements body of with executed: ‘ + self._username);35
36
if __name__ == ‘__main__‘:37
boy = User(‘shouke‘, ‘shouke2014‘)38
print(boy.password)39
with User(‘shouke‘, ‘2014‘) as user:40
print(user.password)41
print(‘---------end-----------‘)42
print(user.password)43
5、闭包:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
closure example
"""
__author__ = "Alpha_Meng"
def line_conf(a, b):
def line(x):
return a * x + b;
return line;
line1 = line_conf(1, 1);
line2 = line_conf(4, 5);
print(line1(5), line2(5));
>>> 6 25xxxxxxxxxx20
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
"""5
closure example6
"""7
8
__author__ = "Alpha_Meng"9
10
def line_conf(a, b):11
def line(x):12
return a * x + b;13
14
return line;15
16
17
line1 = line_conf(1, 1);18
line2 = line_conf(4, 5);19
print(line1(5), line2(5));20
21
22
>>> 6 25不带参数的装饰器:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
decorator example
"""
__author__ = "Alpha_Meng";
# 旧的装饰器(不带参数)
def decorator(func):
def new_func(a, b):
print("input", a, b);
return func(a, b);
return new_func;
# 计算平方和
@decorator
def square_sum(a, b):
return a ** 2 + b ** 2;
# 计算平方差
@decorator
def square_diff(a, b):
return a ** 2 - b ** 2;
print(square_sum(4, 5));
print(square_diff(4, 5));
>>>> input 4 5
>>>> 41
>>>> input 4 5
>>>> -9x
1
39
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
"""5
decorator example6
"""7
8
__author__ = "Alpha_Meng";9
10
11
# 旧的装饰器(不带参数)12
def decorator(func):13
def new_func(a, b):14
print("input", a, b);15
return func(a, b);16
17
return new_func;18
19
# 计算平方和20
21
def square_sum(a, b):22
return a ** 2 + b ** 2;23
24
# 计算平方差25
26
def square_diff(a, b):27
return a ** 2 - b ** 2;28
29
print(square_sum(4, 5));30
print(square_diff(4, 5));31
32
>>>> input 4 533
>>>> 4134
>>>> input 4 535
>>>> -9带参数的装饰器:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
decorator example
"""
__author__ = "Alpha_Meng";
# 新的装饰器(带参数)
def decorator_str(pre=""):
# 旧的装饰器(不带参数)
def decorator(func):
def new_func(a, b):
print(pre + "input", a, b);
return func(a, b);
return new_func;
return decorator;
# 计算平方和
@decorator_str("Hi + ")
def square_sum(a, b):
return a ** 2 + b ** 2;
# 计算平方差
@decorator_str("Hi - ")
def square_diff(a, b):
return a ** 2 - b ** 2;
print(square_sum(4, 5));
print(square_diff(4, 5));
>>> Hi + input 4 5
>>> 41
>>> Hi - input 4 5
>>> -9x
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
"""5
decorator example6
"""7
8
__author__ = "Alpha_Meng";9
10
11
# 新的装饰器(带参数)12
def decorator_str(pre=""):13
# 旧的装饰器(不带参数)14
def decorator(func):15
def new_func(a, b):16
print(pre + "input", a, b);17
return func(a, b);18
return new_func;19
return decorator;20
21
# 计算平方和22
("Hi + ")23
def square_sum(a, b):24
return a ** 2 + b ** 2;25
26
# 计算平方差27
("Hi - ")28
def square_diff(a, b):29
return a ** 2 - b ** 2;30
31
print(square_sum(4, 5));32
print(square_diff(4, 5));33
34
>>> Hi + input 4 535
>>> 4136
>>> Hi - input 4 537
>>> -9类装饰器:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
decorator class example
"""
__author__ = "Alpha_Meng";
def decorator(aClass):
class NewClass():
def __init__(self, age):
self.total_display = 0;
self.wrapped = aClass(age);
def display(self):
self.total_display += 1;
print("total display are called ", self.total_display);
self.wrapped.display();
return NewClass;
@decorator
class Bird():
def __init__(self,age):
self.age = age;
def display(self):
print("the age is ", self.age);
bird = Bird(5);
for i in range(3):
bird.display();
>>> total display are called 1
>>> the age is 5
>>> total display are called 2
>>> the age is 5
>>> total display are called 3
>>> the age is 51
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
"""5
decorator class example6
"""7
8
__author__ = "Alpha_Meng";9
10
11
def decorator(aClass):12
class NewClass():13
def __init__(self, age):14
self.total_display = 0;15
self.wrapped = aClass(age);16
17
def display(self):18
self.total_display += 1;19
print("total display are called ", self.total_display);20
self.wrapped.display();21
22
return NewClass;23
24
25
26
class Bird():27
def __init__(self,age):28
self.age = age;29
30
def display(self):31
print("the age is ", self.age);32
33
bird = Bird(5);34
for i in range(3):35
bird.display();36
37
>>> total display are called 138
>>> the age is 539
>>> total display are called 240
>>> the age is 541
>>> total display are called 342
>>> the age is 57、内存管理
引用计数:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sys import getrefcount;
"""
引用计数
reference count example
"""
__author__ = "Alpha_Meng"
# -------- 引用计数 ---------------
a = [1,2,3];
print(getrefcount(a));
b = [a,a];
print(getrefcount(a));
# ---------对象引用对象,指向同一对象-------------
class FromObj():
def __init__(self,to_obj):
self.to_obj = to_obj;
x = [1,2,3];
y = FromObj(x);
print(id(x));
print(id(y.to_obj));
print(id(x) == id(y.to_obj));
>>> 2
>>> 4
>>> 473473615880
>>> 473473615880
>>> Truex
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
from sys import getrefcount;5
6
"""7
引用计数8
reference count example9
"""10
11
__author__ = "Alpha_Meng"12
13
14
# -------- 引用计数 ---------------15
a = [1,2,3];16
print(getrefcount(a));17
18
b = [a,a];19
print(getrefcount(a));20
21
# ---------对象引用对象,指向同一对象-------------22
23
class FromObj():24
def __init__(self,to_obj):25
self.to_obj = to_obj;26
27
x = [1,2,3];28
y = FromObj(x);29
print(id(x));30
print(id(y.to_obj));31
print(id(x) == id(y.to_obj));32
33
>>> 234
>>> 435
>>> 47347361588036
>>> 47347361588037
>>> TrueGC机制:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sys import getrefcount;
"""
垃圾回收
garbage collection example
到达一个阈值会触发垃圾回收,阈值可以设置。
分代回收策略(分为三代,分为0代,1代,2代),类似java的GC
孤立“引用环”问题:
对象在内存中被删除,需要一个条件:那就是该对象被删除且引用计数为0。
当对象A引用对象B,而对象B又引用对象A,那么会形成一个环状引用。即使删除了对象A和对象B,也不会被删除。
在python 使用了一个机制来解决:
系统中会自动复制对象的引用计数,来单独保存计数。
当对象被删除时,会将对象的所有引用计数都减去1,则即使是环状,也都减成了0。
"""
__author__ = "Alpha_Meng"
a = [];
b = [a];
a.append(b);
print(getrefcount(a))
print(getrefcount(b))
del a;
del b;
print(getrefcount(a))
print(getrefcount(b))
>>> 3
>>> 3
>>> Traceback (most recent call last):
>>> File "F:/python_workspace/zxga/oop/garbage_collection.py", line 36, in <module>
>>> print(getrefcount(a))
>>> NameError: name ‘a‘ is not definedx
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
from sys import getrefcount;5
6
"""7
垃圾回收8
garbage collection example9
10
到达一个阈值会触发垃圾回收,阈值可以设置。11
12
13
分代回收策略(分为三代,分为0代,1代,2代),类似java的GC14
15
孤立“引用环”问题:16
对象在内存中被删除,需要一个条件:那就是该对象被删除且引用计数为0。17
当对象A引用对象B,而对象B又引用对象A,那么会形成一个环状引用。即使删除了对象A和对象B,也不会被删除。18
19
在python 使用了一个机制来解决:20
系统中会自动复制对象的引用计数,来单独保存计数。21
当对象被删除时,会将对象的所有引用计数都减去1,则即使是环状,也都减成了0。22
"""23
24
__author__ = "Alpha_Meng"25
26
a = [];27
b = [a];28
a.append(b);29
30
print(getrefcount(a))31
print(getrefcount(b))32
33
del a;34
del b;35
36
print(getrefcount(a))37
print(getrefcount(b))38
39
>>> 340
>>> 341
>>> Traceback (most recent call last):42
>>> File "F:/python_workspace/zxga/oop/garbage_collection.py", line 36, in <module>43
>>> print(getrefcount(a))44
>>> NameError: name ‘a‘ is not defined8、循环设计
1、循环对象:包含一个next()方法的对象,在穷举完成后,抛出StopIteration错误。
>>> f = open("test.txt");
>>> next(f)
‘123\n‘
>>> next(f)
‘234\n‘
>>> next(f)
‘345‘
>>> next(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIterationxxxxxxxxxx10
1
>>> f = open("test.txt");2
>>> next(f)3
‘123\n‘4
>>> next(f)5
‘234\n‘6
>>> next(f)7
‘345‘8
>>> next(f)9
Traceback (most recent call last):10
File "<stdin>", line 1, in <module>11
StopIteration 2、迭代器: 用iter() 函数返回迭代器对象。
>>> a = [1,2,3]
>>> b = iter(a)
>>> next(b)
1
>>> next(b)
2
>>> next(b)
3
>>> next(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIterationx
1
>>> a = [1,2,3]2
>>> b = iter(a)3
>>> next(b)4
15
>>> next(b)6
27
>>> next(b)8
39
>>> next(b)10
Traceback (most recent call last):11
File "<stdin>", line 1, in <module>12
StopIteration 3、生成器:帮助用户自定义构建循环对象。
yield关键字:程序碰到yield时,会返回;下一次再进入时,从该yield位置后的代码开始执行。
def gen():
a = 10;
yield a;
a = a*10;
yield a;
a = 200;
yield a;
for i in gen():
print(i);
>>> 10
>>> 100
>>> 200xxxxxxxxxx10
1
def gen():2
a = 10;3
yield a;4
a = a*10;5
yield a;6
a = 200;7
yield a;8
9
for i in gen():10
print(i);11
12
>>> 1013
>>> 10014
>>> 200 生成器表达式(generator expression):
# 生成器表达式:
G = (x**2 for x in range(3));
print(next(G))
print(next(G))
print(next(G))
>>> 0
>>> 1
>>> 4xxxxxxxxxx1
# 生成器表达式:2
G = (x**2 for x in range(3));3
print(next(G))4
print(next(G))5
print(next(G))6
7
>>> 08
>>> 19
>>> 4 4、表推导(list comprehension):
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
表推导
list comprehension example
格式如下:
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
列表对象 = [输出的表达式 for i in list if条件]
"""
__author__ = "Alpha_Meng"
list = [i**2 for i in range(10) if i%2 == 1];
print(list)
>>> [1, 9, 25, 49, 81]xxxxxxxxxx21
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
"""5
表推导6
7
list comprehension example8
9
格式如下:10
11
variable = [out_exp_res for out_exp in input_list if out_exp == 2]12
列表对象 = [输出的表达式 for i in list if条件]13
14
"""15
16
__author__ = "Alpha_Meng"17
18
19
list = [i**2 for i in range(10) if i%2 == 1];20
print(list)21
22
>>> [1, 9, 25, 49, 81] 5、除了列表推导式 还有 字典推导式、集合推导式
9、动态类型:
1、值传递 和 址传递(引用传递)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
参数传递
function pass example
"""
__author__ = "Alpha_Meng";
# ------ 值传递 ------
a = 1;
def change_integer(a):
a = a + 1;
return a;
# ------ 引用传递 ------
b = [1, 2, 3]
def change_list(b):
b[0] = b[0] + 1
return b;
print(a);
print(change_integer(a));
print(a);
print(b);
print(change_list(b));
print(b);
>>> 1
>>> 2
>>> 1
>>> [1, 2, 3]
>>> [2, 2, 3]
>>> [2, 2, 3]x
1
#!/usr/bin/env python2
# -*- coding:utf-8 -*-3
4
"""5
参数传递6
function pass example7
"""8
9
__author__ = "Alpha_Meng";10
11
# ------ 值传递 ------12
a = 1;13
14
def change_integer(a):15
a = a + 1;16
return a;17
18
# ------ 引用传递 ------19
b = [1, 2, 3]20
21
def change_list(b):22
b[0] = b[0] + 123
return b;24
25
print(a);26
print(change_integer(a));27
print(a);28
print(b);29
print(change_list(b));30
print(b);31
32
>>> 133
>>> 234
>>> 135
>>> [1, 2, 3]36
>>> [2, 2, 3]37
>>> [2, 2, 3]10、文件读写:
创建文件:
f = open(文件名,模式)
文件对象方法:
读取:f.read(N),f.readLine(),f.readlines()
写入:f.write(str)
关闭:f.close()xxxxxxxxxx1
创建文件:2
f = open(文件名,模式)3
4
文件对象方法:5
读取:f.read(N),f.readLine(),f.readlines()6
写入:f.write(str)7
关闭:f.close()11、OOP常见函数:
- hasattr(o,f) # 查看对象o是否包含f属性
- getattr(o,f) # 获取对象o的f属性
- setattr(o,f,new_f) # 将对象o的f属性设置为new_f
- delattr(o,f) # 删除对象o的f属性
- isinstance(o,c) # 对象o是否为类c的实例
- issubclass(c.par) # 类c是否为类par的子类