[toc]
列表拼接
data 是個(gè)列表或者元組炒嘲,將里面內(nèi)容拼接成字符串顯示
s = "a-b-c-d-e-f"
new_s = "".join(s.split("-"))
不同實(shí)例添加不同的屬性
kwargs = dict(zip([chr(i) for i in range(97, 102)], range(1, 5)))
class Book(object):
def __init__(self, name, authors, price, **kwargs):
self.name = name
self.authors = authors
self.price = price
self.__dict__.update(kwargs) # 更新屬性
b = Book("pythoncookbook", 'smone', 100, **kwargs) # 反解包
默認(rèn)參數(shù)的隱藏寫法
def create_engine(user, passwd, db, host='127.0.0.1', port=3306, **kw):
params = dict(user=user, passwd=passwd, db=db, host=host, port=port)
defaults = dict(use_unicode=True, charset='utf8', collation='utf8_general_ci', autocommit=False)
for k, v in defaults.iteritems():
params[k] = kw.pop(k, v) #kw有值則用kw昌跌,沒有就用 default的
快速讀寫文件(gnenrator)
wwwlog = open("access-log")
bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog) ## 逐行讀入
bytes = (int(x) for x in bytecolumn if x != '-') # 處理
print "Total", sum(bytes)
iostream的打開
打開一個(gè)url文件
from io import StringIO
StringIO(unicode(my_file.read(), "utf-8"))
import io
from PIL import Image
response = urllib2.urlopen('http://images2015.cnblogs.com/blog/425762/201511/425762-20151120204617843-2002471507.png')
val = response.read()
i = Image.open(io.BytesIO(val))
i.save('test.png')
for 循環(huán)添加命令
commands = []
for cmd in "create", "rename", "delete", "search", "copy", "unknown":
commands.append(cmd)
神奇的列表切片
'FizzBuzz'[100:-5:-1]
>>>zzuB
or and not 妙用
a or b 中只有a不為None,空,才會(huì)去求b的值
a and b 兩者皆為True 或有值 ,取后者
def fun_print(x):
print x
return 15165
print 0 or fun_print(123)
print not 1
>>>False
Counter計(jì)數(shù)器
print Counter([1,3,3,3,4,5]) | Counter([3,3,4,5,6]) # 按計(jì)算多的算
list(c.elements())
帶屬性的字典
class Dict(dict):
"""
字典對(duì)象
實(shí)現(xiàn)一個(gè)簡單的可以通過屬性訪問的字典照雁,比如 x.key = value
"""
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
自定義字典類型的數(shù)據(jù)結(jié)構(gòu)
不建議從dict繼承 >http://www.kr41.net/2016/03-23-dont_inherit_python_builtin_dict_type.html
form UserDict import Dictmixin
class CaseInsensitiveDict(DictMixin):
def __init__(self, *args, **kwargs):
# super(CaseInsensitiveDict, self).__init__()
self.data = dict(*args, **kwargs)
def __repr__(self):
return self.data.__repr__()
def __getstate__(self):
return self.data.copy()
def __setstate__(self, d):
self.data = d
def _lower_keys(self):
return map(str.lower, self.data.keys())
def __contains__(self, key):
return key.lower() in self._lower_keys()
def __getitem__(self, key):
if key.lower() in self:
return self.items()[self._lower_keys().index(key.lower())][1]
def __setitem__(self, key, value):
return self.data.__setitem__(key, value)
def __delitem__(self, key):
return self.data.__delitem__(key)
def __keys__(self):
return self.data.__keys__()
def __iter__(self):
return self.data.__iter__()
def iteritems(self):
return self.data.iteritems()
代碼風(fēng)格
http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/
延遲實(shí)例化
class LazyProxy(object):
def __init__(self, cls, *params, **kwargs):
self.__dict__["_cls"]=cls
self.__dict__["_params"]=params
self.__dict__["_kwargs"]=kwargs
self.__dict__["_obj"]=None
def __getattr__(self, name):
if self.__dict__["_obj"] is None:
self.__init_obj()
return getattr(self.__dict__["_obj"], name)
def __setattr__(self, name, value):
if self.__dict__["_obj"] is None:
self.__init_obj()
setattr(self.__dict__["_obj"], name, value)
def __init_obj(self):
self.__dict__["_obj"]=object.__new__(self.__dict__["_cls"], *self.__dict__["_params"], **self.__dict__["_kwargs"])
self.__dict__["_obj"].__init__(*self.__dict__["_params"], **self.__dict__["_kwargs"])
class LazyInit(object):
def __new__(cls, *params, **kwargs):
return LazyProxy(cls, *params, **kwargs)
class A(LazyInit): # classes meant to be lazy loaded are derived from LazyInit
def __init__(self, x):
print("Init A")
self.x=14+x
緩存實(shí)例
和django的cached_property不同蚕愤,可以分別賦值
class cached_property(object):
"""Property descriptor that caches the return value
of the get function.
*Examples*
.. code-block:: python
@cached_property
def connection(self):
return Connection()
@connection.setter # Prepares stored value
def connection(self, value):
if value is None:
raise TypeError('Connection must be a connection')
return value
@connection.deleter
def connection(self, value):
# Additional action to do at del(self.attr)
if value is not None:
print('Connection {0!r} deleted'.format(value)
"""
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.__get = fget
self.__set = fset
self.__del = fdel
self.__doc__ = doc or fget.__doc__
self.__name__ = fget.__name__
self.__module__ = fget.__module__
def __get__(self, obj, type=None):
if obj is None:
return self
try:
return obj.__dict__[self.__name__]
except KeyError:
value = obj.__dict__[self.__name__] = self.__get(obj)
return value
def __set__(self, obj, value):
if obj is None:
return self
if self.__set is not None:
value = self.__set(obj, value)
obj.__dict__[self.__name__] = value
def __delete__(self, obj):
if obj is None:
return self
try:
value = obj.__dict__.pop(self.__name__)
except KeyError:
pass
else:
if self.__del is not None:
self.__del(obj, value)
def setter(self, fset):
return self.__class__(self.__get, fset, self.__del)
def deleter(self, fdel):
return self.__class__(self.__get, self.__set, fdel)
dict(kwargs, **other)
b = {"b": 3}
a = {"a": 1}
c = dict(a, **b)
print c