代码片段.md

2017-08-04  本文已影响0人  brother阿张

[toc]

列表拼接

data 是个列表或者元组,将里面内容拼接成字符串显示

s = "a-b-c-d-e-f"
new_s  = "".join(s.split("-"))

不同实例添加不同的属性

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)  # 反解包

默认参数的隐藏写法

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的打开

打开一个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 循环添加命令

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,空,才会去求b的值
a and b 两者皆为True 或有值 ,取后者

def fun_print(x):
    print x
    return 15165

print 0 or fun_print(123)
print not 1
>>>False

Counter计数器

print Counter([1,3,3,3,4,5]) | Counter([3,3,4,5,6]) # 按计算多的算
list(c.elements())

带属性的字典

class Dict(dict):
    """
    字典对象
    实现一个简单的可以通过属性访问的字典,比如 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

自定义字典类型的数据结构

不建议从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()

代码风格

http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/

延迟实例化

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 

缓存实例

和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
上一篇下一篇

猜你喜欢

热点阅读