先介绍几个类中的应用__getattr__,__setattr__,__get__,__set__,__getattribute__,. __getattr__:当在类中找不到attribute的时候,会调用__getattr__,并执行其中的自定义代码.所有在类中定义的属性都包含在__dict__中,也就是说如果在__dict__中找不到对应的属性名,则__getattr__被触发. class get_try(object):     def __init__(self,value):   …
类和对象: 我们经常会对打印一个对象来得到对象的某些信息. class pair:     def __init__(self,x,y):         self.x=x         self.y=y if __name__=='__main__':     p=pair(3,4)     print p E:\python2.7.11\python.exe E:/py_prj/python_cookbook/chapter8.py <__main__.pair instance at 0…
8.5 私有属性: 在python中,如果想将私有数据封装到类的实例上,有两种方法:1 单下划线.2 双下划线 1 单下划线一般认为是内部实现,但是如果想从外部访问的话也是可以的 2 双下划线是则无法通过外部访问且不能被继承覆盖 来看下面的这个例子: class B: def __init__(self): self.__private=0 def __private_method(self): print("__private method") def public_method(s…
代理类: 代理类的作用其实有继承有些类似,如果你想将某个实例的属性访问代理到内部另外一个实例中去,可以用继承也可以用代理.来看下代理的应用: class A:     def spam(self,x):         print 'in Class A x=%d' % x     def foo(self):         print 'in Class A:foo()' class B1:     def __init__(self):         self._a=A()       …
假设一个工程中有多个类,每个类都通过__init__来初始化参数.但是可能有很多高度重复且样式相同的__init__.为了减少代码.我们可以将初始化数据结构的步骤归纳到一个单独的__init__函数中,并将其定义在一个公共的基类中.示例如下: class structre(): fileds=[] def __init__(self,*args): if len(args) != len(self.fileds): raise TypeError('Expected {} arguments'.…
比如有下面如下的代码,每个函数都需要判断debug的是否为True,而默认的debug为False def a(x,debug=False): if debug: print('calling a') def b(x,y,z,debug=False): if debug: print('calling b') def c(x,y,debug=False): if debug: print('calling c') 上面的代码可以编写一个装饰器为被包装的函数添加额外的参数来简化,但是添加的参数不能…
定义一个属性可由用户修改的装饰器: 在前面的介绍中使用装饰器来包装函数,这一章来介绍下如何让用户调整装饰器的属性. 首先来看下代码: from functools import wraps,partial import logging def attach_wrapper(obj,func=None): if func is None: return partial(attach_wrapper,obj) print(obj) setattr(obj,func.__name__,func) de…
The ideal time to catch an error is at compile time, before you even try to run the program. However, not all errors can be detected at compile time. To create a robust system, each component must be robust. By providing a consistent error-reporting…
python3.4学习笔记(十二) python正则表达式的使用,使用pyspider匹配输出带.html结尾的URL实战例子:使用pyspider匹配输出带.html结尾的URL:@config(age=10 * 24 * 60 * 60)def index_page(self, response): for each in response.doc('a[href^="http"]').items(): matchObj = re.match( r'(.*).html', each…
<Linux命令.编辑器与shell编程>第三版 学习笔记---001 Linux命令.编辑器与shell编程 Shell准备 1.识别Shell类型 echo  $0 echo $BASH echo $SHELL 上边三个命令结果都是: /bin/bash 2.终端常用操作 a.删除单个字符 c+h或退格键 b.删除单个单词 c+w c.删除单个行 c+u d.重复编辑命令行 arrowUp或arrowDown e.中断命令执行c+C 3.切换为root用户 a.su命令后,输入root密码…