一些代码 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命令就能快速的 ...
随机推荐
- 在 Linux 中用 nmcli 命令绑定多块网卡
今天,我们来学习一下在 CentOS 7.x 中如何用 nmcli(Network Manager Command Line Interface:网络管理命令行接口)进行网卡绑定. 网卡(接口)绑定是 ...
- Appcan 3.2 Switch操作
Appcan3.0,有了很多不错的东西,但官方的文档还是那么的不靠谱. 我将记录下,我学习到的东西. 显示2个switch <div class="ub ub-pe"> ...
- codeforces 451E Devu and Flowers
题意:有n个瓶子每个瓶子有 f[i] 支相同的颜色的花(不同瓶子颜色不同,相同瓶子花视为相同) 问要取出s支花有多少种不同方案. 思路: 如果每个瓶子的花有无穷多.那么这个问题可以转化为 s支花分到 ...
- php变量函数,回调函数
一,变量可以直接传递函数 <?php function demo($num , $n )//$n是个函数 { for($i=0;$i<$num;++$i) { if($n($i)) { e ...
- Mobiscroll 3.0 官方同步版
Mobiscroll 3.0 官方同步版发布了. Mobiscroll是一个用于触摸设备的日期和时间选择器,它的使用不会改变HTML5.PhoneGap以及混合应用的原生用户体验.作为一款jQuery ...
- Markov Random Fields
We have seen that directed graphical models specify a factorization of the joint distribution over a ...
- C#面向对象的三大特性
下面是面向对象的本人解析的图片可以让你们更好的理解一下!!! 一,封装: 我们可以把世界上任何一个东西都看作为一个对象,那么我们这里以人为例,一个人就肯定是一个对象了.那么封装是什么呢?封装就是这个人 ...
- layoutSubviews总结
ios layout机制相关方法 - (CGSize)sizeThatFits:(CGSize)size - (void)sizeToFit ——————- - (void)layoutSubview ...
- This tag and its children can be replaced by one <TextView/> and a compound drawable
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...
- cassandra 环境搭建
1 下载安装包 http://www.planetcassandra.org/cassandra/?dlink=http://downloads.datastax.com/community/dsc- ...