一些代码 II (ConfigParser、创建大文件的技巧、__getattr__和__getattribute__、docstring和装饰器、抽象方法)
1. ConfigParser
format.conf
[DEFAULT]
conn_str = %(dbn)s://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s
dbn = mysql
user = root
host = localhost
port = 3306 [db1]
user = aaa
pw = ppp
db = example [db2]
host = 172.16.88.1
pw = www
db = example
readformatini.py
import ConfigParser conf = ConfigParser.ConfigParser()
conf.read('format.conf')
print conf.get('db1', 'conn_str') # mysql://aaa.ppp@localhost:3306/example
print conf.get('db2', 'conn_str') # mysql://root:www@172.16.88.1:3306/example
get(section, option[, raw[, vars]]) 的查找规则如下:
1)如果找不到节点名,就抛出 NoSectionError。
2)如果给定的配置项出现在 get() 方法的 vars 参数中,则返回 vars 参数中的值。
3)如果在指定的节点总含有给定的配置项,则返回其值。
4)如果在 [DEFAULT] 中有指定的配置项,则返回其值。
5)如果在构造函数的 default 参数中有指定的配置项,则返回其值。
6)抛出 NoOptionError。
2. 创建大文件的技巧
f = open('large.csv', 'wb')
f.seek(1073741824-1) # 创建大文件的技巧
f.write('\0')
f.close()
import os
os.stat('large.csv').st_size # 输出文件的大小 1073741824L
大数据的 csv 文件请使用 Pandas 来处理。
3. __getattr__和__getattribute__
# -*- coding:utf-8 -*-
class A(object):
_c = 'test'
def __init__(self):
self.x = None @property
def a(self):
print 'using property to acess attribute'
if self.x is None:
print 'return value'
return 'a'
else:
print 'error occured'
raise AttributeError @a.setter
def a(self, value):
self.x = value def __getattr__(self, name):
print 'using __getattr__ to access attribute'
print 'attribute name:', name
return 'b' def __getattribute__(self, name):
print 'using __getattribute__ to access attribute'
return object.__getattribute__(self, name) a1 = A()
print a1.a
print '--------------'
a1.a = 1
print a1.a
print '--------------'
print A._c
输出如下:
using __getattribute__ to access attribute
using property to acess attribute
using __getattribute__ to access attribute
return value
a
--------------
using __getattribute__ to access attribute
using property to acess attribute
using __getattribute__ to access attribute
error occured
using __getattr__ to access attribute
attribute name: a
b
--------------
test
当实例化 a1 时由于其默认的属性 x 为 None,当我们发你问 a1.a 时,最先搜索的是 __getattribute__() 方法,由于 a 是一个 property 对象,并不存在于 a1 的 dict 中,因此不能返回该方法,此时会搜索 property 中定义的 get() 方法,所以返回的结果是 ‘a’。当用 property 中的 set() 方法对 x 进行修改并再次访问 property 的 get() 方法时会抛出异常,这种情况下回触发对 __getattr__() 方法的调用并返回结果 ‘b’。程序最后访问类变量输出 ‘test’ 是为了说明对类变量的方位不会涉及 __getattribute__() 和 __getattr__() 方法:
注意:__getattribute__() 总会被调用,而__getattr__() 方法仅在如下情况才会被调用:
1)属性不在实例的 __dict__ 中;
2)属性不在其基类以及祖先类的 __dict__ 中;
3)触发 AttributeError 异常时(不仅仅是 __getattribute__() 引发的 AttributeError 异常,property 中定义的 get() 方法抛出异常的时候也会调用该方法)。
4. docstring和装饰器
1 import inspect 2 def is_admin(f):
def wrapper(*args, **kwargs):
func_args = inspect.getcallargs(f, *args, **kwargs) # func_args = {'username': '***', 'type': '***'}
if func_args.get('username') != 'admin':
raise Exception('This user is not allowed to get food')
return f(*args, **kwargs)
return wrapper def foobar(username='someone', type="chocolate"):
"""do crazy stuff"""
pass print foobar.func_doc # do crazy stuff
print foobar.__name__ # foobar @is_admin
def foobar1(username='anyone', type="chocolate"):
""" do another crazy stuff"""
pass print foobar1.__doc__ # None,此时的__doc__应该是wrapper的
print foobar1.__name__ # wrapper
有装饰器的函数会丢失自己的 docstring,使用 functools 中的 wraps 可保留自己的 docstring。将 is_admin() 更改如下即可:
# -*- coding:utf-8 -*-
import functools
import inspect def check_is_admin(f):
@functools.wraps(f) # 注意这行~~~~
def wrapper(*args, **kwargs):
func_args = inspect.getcallargs(f, *args, **kwargs)
print func_args
if func_args.get('username') != 'admin':
raise Exception('This user is not allowed to get food')
return f(*args, **kwargs)
return wrapper
另:inspect 模块允许提取函数签名并对其进行操作。
inspect.getcallargs() 返回一个将参数名字和值作为键值的字典。以上面例子调用 foobar('admin',"rice"),则 func_args 的值为 {'username': 'admin', 'type': 'rice'}
5. 抽象方法
简单的抽象方法:
# -*- coding:utf-8 -*-
class Pizza(object):
@staticmethod
def get_radius():
raise NotImplementedError p = Pizza() # 不报错
p.get_radius() # 报错
实例化时不报错,在真正调用时才报错,报错如下:
Traceback (most recent call last):
File "tt.py", line 8, in <module>
p.get_radius()
File "tt.py", line 5, in get_radius
raise NotImplementedError
NotImplementedError
使用abc实现抽象方法:
# -*- coding:utf-8 -*-
import abc class BasePizza(object):
__metaclass__ = abc.ABCMeta # python2的元类声明方式 @abc.abstractmethod
def get_radius():
"""Method that should do something."""
pass p = BasePizza() # 报错
p.get_radius() # 不执行
类在实例化时就报错,报错如下:
Traceback (most recent call last):
File "tt.py", line 12, in <module>
p = BasePizza()
TypeError: Can't instantiate abstract class BasePizza with abstract methods get_radius
一些代码 II (ConfigParser、创建大文件的技巧、__getattr__和__getattribute__、docstring和装饰器、抽象方法)的更多相关文章
- linux下fallocate快速创建大文件
以前创建文件我一般用dd来创建,例如创建一个512M的文件: dd命令可以轻易实现创建指定大小的文件,如 dd if=/dev/zero of=test bs=1M count=1000 会生成一个1 ...
- Linux系统中创建大文件,并作为文件系统使用
在LInux系统的使用过程中,有时候会遇到诸如某个磁盘分区的大小不够用了,导致其下的文件系统不能正常写入数据.亦或者是系统swap分区太小,不够用或者不满足条件而导致的其他一系列问题.如果我们系统上挂 ...
- rsync增量传输大文件优化技巧
问题 rsync用来同步数据非常的好用,特别是增量同步.但是有一种情况如果不增加特定的参数就不是很好用了.比如你要同步多个几十个G的文件,然后网络突然断开了一下,这时候你重新启动增量同步.但是发现等了 ...
- NAS 创建大文件
不是很懂,但是管用.先记录下来. http://www.111cn.net/sys/linux/55537.htm
- 使用iText库创建PDF文件
前言 译文连接:http://howtodoinjava.com/apache-commons/create-pdf-files-in-java-itext-tutorial/ 对于excel文件的读 ...
- linux使用dd命令快速生成大文件
dd命令可以轻易实现创建指定大小的文件,如 dd if=/dev/zero of=test bs=1M count=1000 会生成一个1000M的test文件,文件内容为全0(因从/dev/zero ...
- Linux使用dd命令快速生成大文件(转)
dd命令可以轻易实现创建指定大小的文件,如 dd if=/dev/zero of=test bs=1M count=1000 会生成一个1000M的test文件,文件内容为全0(因从/dev/zero ...
- 使用dd命令快速生成大文件或者小文件的方法
使用dd命令快速生成大文件或者小文件的方法 转载请说明出处:http://blog.csdn.net/cywosp/article/details/9674757 在程序的测试中有些场 ...
- 使用dd命令快速生成大文件或者小文件
使用dd命令快速生成大文件或者小文件 需求场景: 在程序的测试中有些场景需要大量的小文件或者几个比较大的文件,而在我们的文件系统里一时无法找到那么多或者那么大的文件,此时linux的dd命令就能快速的 ...
随机推荐
- iOS开发拓展篇—UIDynamic(重力行为+碰撞检测)
iOS开发拓展篇—UIDynamic(重力行为+碰撞检测) 一.重力行为 说明:给定重力方向.加速度,让物体朝着重力方向掉落 1.方法 (1)UIGravityBehavior的初始化 - (inst ...
- My Game --线段数据
在背景中用到了一个自定义的类 VectArr : class VectArr { public: VectArr( const Bezier & bz, int conut = 30 ) : ...
- 学习Nim语言.rar(nim语言中文教程下载)
学习Nim语言 nim 语法上类似python ,是一门静态编译型语言,nim 使用空格缩进标示语句块的开始和结束, 喜欢python风格的程序员应该也会很容易适应和喜欢nim的风格. nim语言官方 ...
- Jquery EasyUI DataGrid .net实例
前台界面:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...
- priority_queue 优先队列用法
//采用默认优先关系: //(priority_queue<int>que;) //Queue 0: // 91 83 72 56 47 36 22 14 10 7 3 // //采用结构 ...
- JavaScript 运行时错误: 无法获取未定义或 null 一种解决方案
脚本是肯定没有错误的!! 引用了高版本的jquery jquery-1.10.1.min.js 但在ie10下面就是报错 "JavaScript 运行时错误: 无法获取未定义或 null & ...
- addslashes() 函数和stripslashes()函数
addslashes() 函数 定义和用法 addslashes() 函数在指定的预定义字符前添加反斜杠. 这些预定义字符是: 单引号 (') 双引号 (") 反斜杠 (\) NULL 语法 ...
- Android GPS定位 获取经纬度
移动 是手机与手持设备的最大特点,可以通过Eclipse的DDMS视图,模拟设备的位置变化,改变经纬度后,点击send,然后运行程序,在应用程序中,动态的获取设备位置,然后显示当前的位置信息. 获取位 ...
- Smart210学习记录----nand flash驱动
[详解]如何编写Linux下Nand Flash驱动 :http://www.cnblogs.com/linux-rookie/articles/3016990.html 当读写文件请求到来的时候, ...
- sge学习 (转)
转自http://biancheng.dnbcw.info/linux/417992.html 命令: qsub - submit a batch job to Grid Engine. qsh ...