Python基础测试与笔记(二)

1. 高阶函数

# 类似于递归函数,常见于Java,C#自定义接口中
def cmd_ignore_case(s1,s2)
    u1 = s1.upper()
    u2 = s2.upper()
    if u1 < u2:
        return -1
    if u1 > u2:
        return 1
    return 0
sorted([‘about‘,‘bobo‘,‘Zone‘,‘dangerous‘], cmd_ignore_case)

2. 面向对象---定义

# 面向对象
class Student(object):
    pass
# 实例绑定一个属性:
s = Student()
s.name = ‘King‘
# 定义一个函数作为实例方法
from types import MethodType
s.set_age = MethodType(set_age, s, Student)
# 所有实例全部绑定方法
Student.set_score = MethodType(set_score, None, Student)

3. 对象的浅拷贝与深拷贝

# 谈论这个话题的就只有对象了 list , tuple , class , dict  etc
# 浅拷贝  只复制对象的值(或者说被引用)
1. 切片  list[:]
2. 工厂函数  list() dict()
3. copy模块的copy函数
# 深拷贝  复制值还要另开辟新的空间地址
1. copy模块的deepcopy函数

4. 面向对象---属性

class Student(object):
    # 此处特殊的写法 @ 就是装饰器的用法
    # 此属性有 getter,setter 操作类的成员
    @property
    def score(self):
        return self._score
    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError(‘score must be an integer!‘)
        if value < 0 or value > 100:
            raise ValueError(‘score must between 0 ~ 100!‘)
        self._score = value

5. 面向对象---多重继承 Minix

class animal(object):
    @property
    def alive(self):
        return self._alive
    @alive.setter
    def alive(self, value):
        self._alive = value
                                                       
class bunkMinix(object):
    def bunk(self):
        print(‘bunk‘)
# 这里的dog对象不但继承了animal还继承实现了bunkMinix
class dog(animal, bunkMinix):
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, value):
        self._name = value
.
.
# mixin多重继承   主线一般是单继承
class Dog(Mammal, bunkMinix, eatMixin):
    pass

6. 类的常用内置函数

# 用tuple定义允许绑定的属性名称
__slots__ = (‘name‘, ‘age‘)
.
# 默认类的调用打印信息    dog()
__str__   类似于Java语言   toString()
.
# 调试信息给开发者看
__repr__   类似于C#语言   @debug
.
# 迭代如果有可iter元素
__iter__    类似与C#语言   IEnumerable接口概念
# 出现了__iter__就必须要出现 next() 方法
例:
class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1 # 初始化两个计数器a,b
    def __iter__(self):
        return self # 实例本身就是迭代对象,故返回自己
    def next(self):
        self.a, self.b = self.b, self.a + self.b # 计算下一个值
        if self.a > 100000: # 退出循环的条件
            raise StopIteration();
        return self.a # 返回下一个值
.
# __getitem__     取iter单个元素     类似与C#语言  对象索引器
class Fib(object):
    def __getitem__(self, n):
        a, b = 1, 1
        for x in range(n):
            a, b = b, a + b
        return a
.
__getattr__      动态返回对象中没有定义的属性
class Student(object):
    def __init__(self):
        self.name = ‘Michael‘
    def __getattr__(self, attr):
        if attr==‘score‘:
            return 99
.
# 判断类是否能被调用
__call__      callable()  
例:
def __call__(self):
    print(‘My name is %s.‘ % self.name)
s = Student(‘King‘)
s()

7. 异常处理

#  try..catch..finnlly
try:
    print ‘try...‘
    r = 10 / 0
    print ‘result:‘, r
except ZeroDivisionError, e:
    print ‘except:‘, e
finally:
    print ‘finally...‘
print ‘END‘
.
# 自定义异常处理
class FooError(StandardError):
    print(‘这是一个自定义错误!!‘)
def foo(s):
    n = int(s)
    if n==0:
        raise FooError(‘invalid value: %s‘ % s)
    return 10 / n

8. 调试

# 开启命令行调试功能
python -m pdb err.py
l  查看当前代码
变量名  查看当前变量的值
q  退出调试功能
n  调试到下一步
n m  调试器走几步
# 调试器从代码开头运行到最后,万一代码多怎么办?
# 需要调试的地方加入
import pdb
pdb.set_trace()

9. 文件读写

# 文件读 默认是只读状态打开文件
f = open(‘/Users/King/hhvm.conf‘)
print f.read(30)
for line in f.readlines():
    print(line.strip()) # 把末尾的‘\n‘删掉
f.close()
#
# with可以偷懒少掉 close() 这一步
with open(‘/Users/King/hhvm.conf‘, ‘r‘) as f:
    print f.read()
#
# 二进制模式要加 b
f = open(‘/Users/King/test.jpg‘, ‘rb‘)
f.read()
#
# 要读取非ASCII编码的文本文件,就必须以二进制模式打开,再解码。
f = open(‘/Users/King/gbk.txt‘, ‘rb‘)
u = f.read().decode(‘gbk‘)
print u
#
# 文件编码的另一种解决方案
import codecs
with codecs.open(‘/Users/King/gbk.txt‘, ‘r‘, ‘gbk‘) as f:
    f.read() # u‘\u6d4b\u8bd5‘
#
# 文件写  模式替换为 w
# 对应方法为   wirte  writeLine  编码与读雷同也有两种方案


测试: 如果你能看懂下面的代码,证明初级部分的Python已经没有问题,接下来就是Python标准库的学习了

import time
import threading
import Queue
#
class Controm(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue
#
    def run(self):
        while True:
            msg = self._queue.get()
            if isinstance(msg, str) and msg == ‘quit‘:
                break
            print ‘client message %s‘ % msg
        print ‘bye‘
#
def Proceser():
    queue = Queue.Queue()
    worker = Controm(queue)
    worker.start()
#
    start_time = time.time()
    while time.time() - start_time < 5:
        queue.put(‘msg %s‘ % time.time())
        time.sleep(1)
    queue.put(‘quit‘)
#
    worker.join()
#
if __name__ == ‘__main__‘:
    Proceser()



Update: 后续会进行Python标准库的更新...

本文出自 “Apprentice” 博客,请务必保留此出处http://apprentice.blog.51cto.com/2214645/1391811

Python基础测试与笔记(二),古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。