一些代码 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命令就能快速的 ...
随机推荐
- ORM原型概念
ORM[Object-Relation-Mapping]对象关系映射. 这个名词已经出来好几年了.已经不陌生. 以前在项目中针对相对复杂业务逻辑时一般采用领域模型驱动方式进行业务概述,分析和建模. ...
- C# 文件夹加密
可以加密文件内容,也可以对文件夹本身进行加密,本文对文件夹加密. 一.指定或生成一个密钥 1)指定的密钥 /// <summary> /// 密钥,这个密码可以随便指定 /// </ ...
- warning: incompatible implicit declaration of built-in function ‘exit’
出现这个错误,一般是程序中某个函数没有include相关的文件. EG. 出现这个错误是因为要使用exit()应该包含stdlib.h文件
- flexslider
flexslider是一个出色的jquery滑动切换插件,支持主流浏览器,并有淡入淡出效果.适合初级和高级网页设计师. 查询了网上资料 总结一下flexslider属性 $(function(){ ...
- CSS行内元素和块级元素的居中
一.水平居中 行内元素和块级元素不同,对于行内元素,只需在父元素中设置text-align=center即可; 对于块级元素有以下几种居中方式: 1.将元素放置在table中,再将table的marg ...
- source insight shift+tab问题
之前用的好好的,shift+tab功能为向左缩进(即tab的相反功能),但是突然就有问题了:现象为只是光标向左移动,但文本不动. 解决方法: 1 使用快捷键f9 2 重新定义快捷键,把shift+ta ...
- Python Scarpy安装包
由于网络的原因,Scraoy无法安装 Cannot fetch index base URL https://pypi.python.org/simple/ 1. scrapy 安装所需要的包可以从 ...
- iOS红马甲项目开发过程Bug总结(1)
在上线审核时,重新检测自己的app发现报错:"was compiled with optimization - steppingmay behave oddly; variables may ...
- dp常见模型
1.背包问题.0/1背包.完全背包.多重背包.分组背包.依赖背包. 2.子序列.最长非上升/下降子序列.最长先上升再下降子序列.最长公共子序列.最大连续子区间和. 3.最大子矩阵. 4.区间dp. 5 ...
- 【ZJOI2004】嗅探器
练tarjian不错的题,连WA几次后终于会记住tarjian的模板了 原题: 某军搞信息对抗实战演习.红军成功地侵入了蓝军的内部网络.蓝军共有两个信息中心.红军计划在某台中间服务器上安装一个嗅探器, ...