1. Item 38: 淺談 Python 3.3 的 Yield From 表達式

    我最近需要使用 Python 2.7 解開 zip 壓縮檔並分析檔案內容。所以我寫了下面的程式。然而這個程式是有問題的。它沒有辦法列出 zip 壓縮檔裡面的檔案。為什麼呢?

    #!/usr/bin/env python
    
    import os
    import shutil
    import sys
    import tempfile
    import zipfile
    
    def unzip(zip_file_path, out_dir):
        with zipfile.ZipFile(zip_file_path) as zip_file:
            zip_file.extractall(out_dir)
    
    def list_files(path):
        for base, _, filenames in os.walk …

    More

  2. Item 37: Finalize

    如果我們要讓一個物件持有一些資源,然後希望這個物件被回收的時候釋放它持有的資源,我們該怎麼撰寫這個類別呢?舉例來說,TemporaryDirectory 類別會在建構實例的時候,使用 tempfile.mkdtemp() 產生一個暫時資料夾。當 TemporaryDirectory 的實例死亡後,會呼叫 shutil.rmtree() 刪除對應的暫時資料夾。我們該怎麼實作 TemporaryDirectory 呢?

    簡單的想法

    一個簡單的想法是定義類別的建構函式與解構函式。我們可以在 __init__() 方法(建構函式)中呼叫 tempfile.mkdtemp();另外在 __del__() 方法(解構函式)呼叫 shutil.rmtree()

    #!/usr/bin/env python3
    import shutil
    import tempfile
    
    class TemporaryDirectory(object):
        def __init__(self …

    More

  3. Item 36: Raise From

    今天要介紹 Python 3 引入的 raise ... from ... 述句。相信大家都知道 raise 述句是用來拋出一個例外。那 raise ... from ... 述句有何不同呢?

    #!/usr/bin/env python3
    import traceback
    
    class TestError(ValueError):
        pass
    
    def test(buf):
        try:
            return (buf[2], buf[3])
        except IndexError as e:
            raise TestError() from e
    
    try:
        test(b'')
    except Exception as e:
        print('cause …

    More

  4. Item 35: getitem, setitem, and contains

    from collections import defaultdict
    
    class PrintDict(defaultdict):
        def __getitem__(self, key):
            print('getitem:', 'before:', key)
            value = super().__getitem__(key)
            print('getitem:', 'after:', key, value)
            return value
        def __contains__(self, key):
            print('contains:', 'before:', key)
            value = super().__contains__(key)
            print('contains:', 'after:', key, value)
            return value
        def __setitem__(self, key, value …

    More

  5. Item 34: defaultdict

    from collections import defaultdict
    from itertools import repeat
    import re
    
    input_data = '''
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.'''
    
    word_freq = defaultdict(repeat(0).__next__)
    for word in re.findall('\\w+', input_data):
        word_freq[word.lower()] += 1
    
    freq_words = defaultdict(list …

    More

  6. Item 33: dict.setdefault() Method

    import re
    
    input_data = '''
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.'''
    
    word_freq = dict()
    for word in re.findall('\\w+', input_data):
        word_freq.setdefault(word.lower(), 0)
        word_freq[word.lower()] += 1
    
    freq_words = dict()
    for word, freq in word_freq.items():
        freq_words …

    More

  7. Item 32: namedtuple

    from collections import namedtuple
    
    Person = namedtuple('Person', ('id', 'role', 'name'))
    print(Person)
    people = [
        Person(1, 'Research', 'Ada Lovelace'),
        Person(2, 'Scientist', 'Grace Hopper'),
        Person._make((3, 'Poet', 'Emily Dickinson')),
        Person._make([4, 'Biologist', 'Rachel Carson']),
    ]
    
    for p in people:
        print('R:', p)
        print('P:', p.id, p.role, p.name …

    More

  8. Item 31: Property Override

    class A(object):
        def __init__(self, x):
            self.x = x
    
        def _get_y(self):
            return self.x * 2
        y = property(_get_y)
    
        def _get_z(self):
            return self.x * 2
        def __get_z(self):
            return self._get_z()
        z = property(__get_z)
    
    class B(A):
        def _get_y(self):
            return self.x * 3
        #y = property(_get_y)
        def …

    More

  9. Item 30: Callable

    class Action(object):
        def __init__(self, name):
            self.name = name
    
        def __call__(self, *args, **kwargs):
            print(self.name, *args, **kwargs)
    
    actions = [
        Action('Hello'),
        Action('Bonjour'),
        Action('Goodbye'),
    ]
    
    for action in actions:
        action('world')
    

    More

  10. Item 29: More Bound Method

    class EventHandler(object):
        def __init__(self, name):
            self.name = name
        def test1(self, *args, **kwargs):
            print('test1:', self.name, *args, **kwargs)
        def test2(self, *args, **kwargs):
            print('test2:', self.name, *args, **kwargs)
    
    # test3() is a normal function, not enclosed by class statement.
    def test3(self, *args, **kwargs):
        print('test3:', self …

    More

Page 1 / 4 Next »