Full Code of youngsterxyf/mpdp-code for AI

master 282e13bac4b6 cached
31 files
49.1 KB
13.2k tokens
294 symbols
1 requests
Download .txt
Repository: youngsterxyf/mpdp-code
Branch: master
Commit: 282e13bac4b6
Files: 31
Total size: 49.1 KB

Directory structure:
gitextract_hdfimttc/

├── chapter1/
│   ├── abstract_factory.py
│   ├── data/
│   │   ├── donut.json
│   │   └── person.xml
│   ├── factory_method.py
│   └── id.py
├── chapter10/
│   └── chain.py
├── chapter11/
│   ├── command.py
│   └── first-class.py
├── chapter12/
│   └── interpreter.py
├── chapter13/
│   └── observer.py
├── chapter14/
│   └── state.py
├── chapter15/
│   ├── langs.py
│   └── strategy.py
├── chapter16/
│   ├── graph.py
│   ├── graph_template.py
│   ├── graph_template_slower.py
│   └── template.py
├── chapter2/
│   ├── apple-factory.py
│   ├── builder.py
│   ├── builder2.py
│   └── computer-builder.py
├── chapter3/
│   ├── clone.py
│   └── prototype.py
├── chapter4/
│   ├── adapter.py
│   └── external.py
├── chapter5/
│   └── mymath.py
├── chapter6/
│   └── facade.py
├── chapter7/
│   └── flyweight.py
├── chapter8/
│   └── mvc.py
└── chapter9/
    ├── lazy.py
    └── proxy.py

================================================
FILE CONTENTS
================================================

================================================
FILE: chapter1/abstract_factory.py
================================================
class Frog:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def interact_with(self, obstacle):
        print('{} the Frog encounters {} and {}!'.format(self,
                                                         obstacle, obstacle.action()))


class Bug:

    def __str__(self):
        return 'a bug'

    def action(self):
        return 'eats it'


class FrogWorld:

    def __init__(self, name):
        print(self)
        self.player_name = name

    def __str__(self):
        return '\n\n\t------ Frog World ———'

    def make_character(self):
        return Frog(self.player_name)

    def make_obstacle(self):
        return Bug()


class Wizard:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

    def interact_with(self, obstacle):
        print('{} the Wizard battles against {} and {}!'.format(self, obstacle, obstacle.action()))


class Ork:

    def __str__(self):
        return 'an evil ork'

    def action(self):
        return 'kills it'


class WizardWorld:

    def __init__(self, name):
        print(self)
        self.player_name = name

    def __str__(self):
        return '\n\n\t------ Wizard World ———'

    def make_character(self):
        return Wizard(self.player_name)

    def make_obstacle(self):
        return Ork()


class GameEnvironment:

    def __init__(self, factory):
        self.hero = factory.make_character()
        self.obstacle = factory.make_obstacle()

    def play(self):
        self.hero.interact_with(self.obstacle)


def validate_age(name):
    try:
        age = input('Welcome {}. How old are you? '.format(name))
        age = int(age)
    except ValueError as err:
        print("Age {} is invalid, please try \
        again…".format(age))
        return (False, age)
    return (True, age)


def main():
    name = input("Hello. What's your name? ")
    valid_input = False
    while not valid_input:
        valid_input, age = validate_age(name)
    game = FrogWorld if age < 18 else WizardWorld
    environment = GameEnvironment(game(name))
    environment.play()

if __name__ == '__main__':
    main()


================================================
FILE: chapter1/data/donut.json
================================================
[
    {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters": {
            "batter": [
                {
                    "id": "1001",
                    "type": "Regular"
                },
                {
                    "id": "1002",
                    "type": "Chocolate"
                },
                {
                    "id": "1003",
                    "type": "Blueberry"
                },
                {
                    "id": "1004",
                    "type": "Devil's Food"
                }
            ]
        },
        "topping": [
            {
                "id": "5001",
                "type": "None"
            },
            {
                "id": "5002",
                "type": "Glazed"
            },
            {
                "id": "5005",
                "type": "Sugar"
            },
            {
                "id": "5007",
                "type": "Powdered Sugar"
            },
            {
                "id": "5006",
                "type": "Chocolate with Sprinkles"
            },
            {
                "id": "5003",
                "type": "Chocolate"
            },
            {
                "id": "5004",
                "type": "Maple"
            }
        ]
    },
    {
        "id": "0002",
        "type": "donut",
        "name": "Raised",
        "ppu": 0.55,
        "batters": {
            "batter": [
                {
                    "id": "1001",
                    "type": "Regular"
                }
            ]
        },
        "topping": [
            {
                "id": "5001",
                "type": "None"
            },
            {
                "id": "5002",
                "type": "Glazed"
            },
            {
                "id": "5005",
                "type": "Sugar"
            },
            {
                "id": "5003",
                "type": "Chocolate"
            },
            {
                "id": "5004",
                "type": "Maple"
            }
        ]
    },
    {
        "id": "0003",
        "type": "donut",
        "name": "Old Fashioned",
        "ppu": 0.55,
        "batters": {
            "batter": [
                {
                    "id": "1001",
                    "type": "Regular"
                },
                {
                    "id": "1002",
                    "type": "Chocolate"
                }
            ]
        },
        "topping": [
            {
                "id": "5001",
                "type": "None"
            },
            {
                "id": "5002",
                "type": "Glazed"
            },
            {
                "id": "5003",
                "type": "Chocolate"
            },
            {
                "id": "5004",
                "type": "Maple"
            }
        ]
    }
]

================================================
FILE: chapter1/data/person.xml
================================================
<persons>
     <person>
       <firstName>John</firstName>
       <lastName>Smith</lastName>
       <age>25</age>
       <address>
         <streetAddress>21 2nd Street</streetAddress>
         <city>New York</city>
         <state>NY</state>
         <postalCode>10021</postalCode>
       </address>
       <phoneNumbers>
         <phoneNumber type="home">212 555-1234</phoneNumber>
         <phoneNumber type="fax">646 555-4567</phoneNumber>
       </phoneNumbers>
       <gender>
         <type>male</type>
       </gender>
     </person>
     <person>
       <firstName>Jimy</firstName>
       <lastName>Liar</lastName>
    <age>19</age>
    <address>
      <streetAddress>18 2nd Street</streetAddress>
      <city>New York</city>
      <state>NY</state>
      <postalCode>10021</postalCode>
    </address>
    <phoneNumbers>
      <phoneNumber type="home">212 555-1234</phoneNumber>
    </phoneNumbers>
    <gender>
      <type>male</type>
    </gender>
  </person>
  <person>
    <firstName>Patty</firstName>
    <lastName>Liar</lastName>
    <age>20</age>
    <address>
      <streetAddress>18 2nd Street</streetAddress>
      <city>New York</city>
      <state>NY</state>
      <postalCode>10021</postalCode>
    </address>
    <phoneNumbers>
      <phoneNumber type="home">212 555-1234</phoneNumber>
      <phoneNumber type="mobile">001 452-8819</phoneNumber>
    </phoneNumbers>
    <gender>
      <type>female</type>
    </gender>
  </person>
</persons>

================================================
FILE: chapter1/factory_method.py
================================================
import xml.etree.ElementTree as etree
import json


class JSONConnector:

    def __init__(self, filepath):
        self.data = dict()
        with open(filepath, mode='r', encoding='utf-8') as f:
            self.data = json.load(f)

    @property
    def parsed_data(self):
        return self.data


class XMLConnector:

    def __init__(self, filepath):
        self.tree = etree.parse(filepath)

    @property
    def parsed_data(self):
        return self.tree


def connection_factory(filepath):
    if filepath.endswith('json'):
        connector = JSONConnector
    elif filepath.endswith('xml'):
        connector = XMLConnector
    else:
        raise ValueError('Cannot connect to {}'.format(filepath))
    return connector(filepath)


def connect_to(filepath):
    factory = None
    try:
        factory = connection_factory(filepath)
    except ValueError as ve:
        print(ve)
    return factory


def main():
    sqlite_factory = connect_to('data/person.sq3')
    print()

    xml_factory = connect_to('data/person.xml')
    xml_data = xml_factory.parsed_data
    liars = xml_data.findall(".//{}[{}='{}']".format('person',
                                                     'lastName', 'Liar'))
    print('found: {} persons'.format(len(liars)))
    for liar in liars:
        print('first name: {}'.format(liar.find('firstName').text))
        print('last name: {}'.format(liar.find('lastName').text))
        [print('phone number ({})'.format(p.attrib['type']),
               p.text) for p in liar.find('phoneNumbers')]

    print()

    json_factory = connect_to('data/donut.json')
    json_data = json_factory.parsed_data
    print('found: {} donuts'.format(len(json_data)))
    for donut in json_data:
        print('name: {}'.format(donut['name']))
        print('price: ${}'.format(donut['ppu']))
        [print('topping: {} {}'.format(t['id'], t['type'])) for t in donut['topping']]

if __name__ == '__main__':
    main()


================================================
FILE: chapter1/id.py
================================================
class A(object):
    pass

if __name__ == '__main__':
    a = A()
    b = A()

    print(id(a) == id(b))
    print(a, b)


================================================
FILE: chapter10/chain.py
================================================
class Event:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name


class Widget:

    def __init__(self, parent=None):
        self.parent = parent

    def handle(self, event):
        handler = 'handle_{}'.format(event)
        if hasattr(self, handler):
            method = getattr(self, handler)
            method(event)
        elif self.parent:
            self.parent.handle(event)
        elif hasattr(self, 'handle_default'):
            self.handle_default(event)


class MainWindow(Widget):

    def handle_close(self, event):
        print('MainWindow: {}'.format(event))

    def handle_default(self, event):
        print('MainWindow Default: {}'.format(event))


class SendDialog(Widget):

    def handle_paint(self, event):
        print('SendDialog: {}'.format(event))


class MsgText(Widget):

    def handle_down(self, event):
        print('MsgText: {}'.format(event))


def main():
    mw = MainWindow()
    sd = SendDialog(mw)
    msg = MsgText(sd)

    for e in ('down', 'paint', 'unhandled', 'close'):
        evt = Event(e)
        print('\nSending event -{}- to MainWindow'.format(evt))
        mw.handle(evt)
        print('Sending event -{}- to SendDialog'.format(evt))
        sd.handle(evt)
        print('Sending event -{}- to MsgText'.format(evt))
        msg.handle(evt)

if __name__ == '__main__':
    main()


================================================
FILE: chapter11/command.py
================================================
import os

verbose = True


class RenameFile:

    def __init__(self, path_src, path_dest):
        self.src, self.dest = path_src, path_dest

    def execute(self):
        if verbose:
            print("[renaming '{}' to '{}']".format(self.src, self.dest))
        os.rename(self.src, self.dest)

    def undo(self):
        if verbose:
            print("[renaming '{}' back to '{}']".format(self.dest, self.src))
        os.rename(self.dest, self.src)


class CreateFile:

    def __init__(self, path, txt='hello world\n'):
        self.path, self.txt = path, txt

    def execute(self):
        if verbose:
            print("[creating file '{}']".format(self.path))
        with open(self.path, mode='w', encoding='utf-8') as out_file:
            out_file.write(self.txt)

    def undo(self):
        delete_file(self.path)


class ReadFile:

    def __init__(self, path):
        self.path = path

    def execute(self):
        if verbose:
            print("[reading file '{}']".format(self.path))
        with open(self.path, mode='r', encoding='utf-8') as in_file:
            print(in_file.read(), end='')


def delete_file(path):
    if verbose:
        print("deleting file '{}'".format(path))
    os.remove(path)


def main():
    orig_name, new_name = 'file1', 'file2'

    commands = []
    for cmd in CreateFile(orig_name), ReadFile(orig_name), RenameFile(orig_name, new_name):
        commands.append(cmd)

    [c.execute() for c in commands]

    answer = input('reverse the executed commands? [y/n] ')

    if answer not in 'yY':
        print("the result is {}".format(new_name))
        exit()

    for c in reversed(commands):
        try:
            c.undo()
        except AttributeError as e:
            pass

if __name__ == '__main__':
    main()


================================================
FILE: chapter11/first-class.py
================================================
import os

verbose = True


class RenameFile:

    def __init__(self, path_src, path_dest):
        self.src, self.dest = path_src, path_dest

    def execute(self):
        if verbose:
            print("[renaming '{}' to '{}']".format(self.src, self.dest))
        os.rename(self.src, self.dest)

    def undo(self):
        if verbose:
            print("[renaming '{}' back to '{}']".format(self.dest, self.src))
        os.rename(self.dest, self.src)


class CreateFile:

    def __init__(self, path, txt='hello world\n'):
        self.path, self.txt = path, txt

    def execute(self):
        if verbose:
            print("[creating file '{}']".format(self.path))
        with open(self.path, mode='w', encoding='utf-8') as out_file:
            out_file.write(self.txt)

    def undo(self):
        delete_file(self.path)


class ReadFile:

    def __init__(self, path):
        self.path = path

    def execute(self):
        if verbose:
            print("[reading file '{}']".format(self.path))
        with open(self.path, mode='r', encoding='utf-8') as in_file:
            print(in_file.read(), end='')


def delete_file(path):
    if verbose:
        print("deleting file '{}'".format(path))
    os.remove(path)


def main():
    orig_name = 'file1'
    df = delete_file

    commands = []
    commands.append(df)

    for c in commands:
        try:
            c.execute()
        except AttributeError as e:
            df(orig_name)

    for c in reversed(commands):
        try:
            c.undo()
        except AttributeError as e:
            pass

if __name__ == '__main__':
    '''
    译注:这个程序会异常退出
    '''
    main()


================================================
FILE: chapter12/interpreter.py
================================================
# coding: utf-8

from pyparsing import Word, OneOrMore, Optional, Group, Suppress, alphanums


class Gate:

    def __init__(self):
        self.is_open = False

    def __str__(self):
        return 'open' if self.is_open else 'closed'

    def open(self):
        print('opening the gate')
        self.is_open = True

    def close(self):
        print('closing the gate')
        self.is_open = False


class Garage:

    def __init__(self):
        self.is_open = False

    def __str__(self):
        return 'open' if self.is_open else 'closed'

    def open(self):
        print('opening the garage')
        self.is_open = True

    def close(self):
        print('closing the garage')
        self.is_open = False


class Aircondition:

    def __init__(self):
        self.is_on = False

    def __str__(self):
        return 'on' if self.is_on else 'off'

    def turn_on(self):
        print('turning on the aircondition')
        self.is_on = True

    def turn_off(self):
        print('turning off the aircondition')
        self.is_on = False


class Heating:

    def __init__(self):
        self.is_on = False

    def __str__(self):
        return 'on' if self.is_on else 'off'

    def turn_on(self):
        print('turning on the heating')
        self.is_on = True

    def turn_off(self):
        print('turning off the heating')
        self.is_on = False


class Boiler:

    def __init__(self):
        self.temperature = 83  # in celsius

    def __str__(self):
        return 'boiler temperature: {}'.format(self.temperature)

    def increase_temperature(self, amount):
        print("increasing the boiler's temperature by {} degrees".format(amount))
        self.temperature += amount

    def decrease_temperature(self, amount):
        print("decreasing the boiler's temperature by {} degrees".format(amount))
        self.temperature -= amount


class Fridge:

    def __init__(self):
        self.temperature = 2  # 单位为摄氏度

    def __str__(self):
        return 'fridge temperature: {}'.format(self.temperature)

    def increase_temperature(self, amount):
        print("increasing the fridge's temperature by {} degrees".format(amount))
        self.temperature += amount

    def decrease_temperature(self, amount):
        print("decreasing the fridge's temperature by {} degrees".format(amount))
        self.temperature -= amount


def main():
    word = Word(alphanums)
    command = Group(OneOrMore(word))
    token = Suppress("->")
    device = Group(OneOrMore(word))
    argument = Group(OneOrMore(word))
    event = command + token + device + Optional(token + argument)

    gate = Gate()
    garage = Garage()
    airco = Aircondition()
    heating = Heating()
    boiler = Boiler()
    fridge = Fridge()

    tests = ('open -> gate',
             'close -> garage',
             'turn on -> aircondition',
             'turn off -> heating',
             'increase -> boiler temperature -> 5 degrees',
             'decrease -> fridge temperature -> 2 degrees')
    open_actions = {'gate': gate.open,
                    'garage': garage.open,
                    'aircondition': airco.turn_on,
                    'heating': heating.turn_on,
                    'boiler temperature': boiler.increase_temperature,
                    'fridge temperature': fridge.increase_temperature}
    close_actions = {'gate': gate.close,
                     'garage': garage.close,
                     'aircondition': airco.turn_off,
                     'heating': heating.turn_off,
                     'boiler temperature': boiler.decrease_temperature,
                     'fridge temperature': fridge.decrease_temperature}

    for t in tests:
        if len(event.parseString(t)) == 2:  # 没有参数
            cmd, dev = event.parseString(t)
            cmd_str, dev_str = ' '.join(cmd), ' '.join(dev)
            if 'open' in cmd_str or 'turn on' in cmd_str:
                open_actions[dev_str]()
            elif 'close' in cmd_str or 'turn off' in cmd_str:
                close_actions[dev_str]()
        elif len(event.parseString(t)) == 3:  # 有参数
            cmd, dev, arg = event.parseString(t)
            cmd_str, dev_str, arg_str = ' '.join(cmd), ' '.join(dev), ' '.join(arg)
            num_arg = 0
            try:
                num_arg = int(arg_str.split()[0])  # 抽取数值部分
            except ValueError as err:
                print("expected number but got: '{}'".format(arg_str[0]))
            if 'increase' in cmd_str and num_arg > 0:
                open_actions[dev_str](num_arg)
            elif 'decrease' in cmd_str and num_arg > 0:
                close_actions[dev_str](num_arg)

if __name__ == '__main__':
    main()


================================================
FILE: chapter13/observer.py
================================================
class Publisher:

    def __init__(self):
        self.observers = []

    def add(self, observer):
        if observer not in self.observers:
            self.observers.append(observer)
        else:
            print('Failed to add: {}'.format(observer))

    def remove(self, observer):
        try:
            self.observers.remove(observer)
        except ValueError:
            print('Failed to remove: {}'.format(observer))

    def notify(self):
        [o.notify(self) for o in self.observers]


class DefaultFormatter(Publisher):

    def __init__(self, name):
        Publisher.__init__(self)
        self.name = name
        self._data = 0

    def __str__(self):
        return "{}: '{}' has data = {}".format(type(self).__name__, self.name, self._data)

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, new_value):
        try:
            self._data = int(new_value)
        except ValueError as e:
            print('Error: {}'.format(e))
        else:
            self.notify()


class HexFormatter:

    def notify(self, publisher):
        print("{}: '{}' has now hex data = {}".format(type(self).__name__,
                                                      publisher.name, hex(publisher.data)))


class BinaryFormatter:

    def notify(self, publisher):
        print("{}: '{}' has now bin data = {}".format(type(self).__name__,
                                                      publisher.name, bin(publisher.data)))


def main():
    df = DefaultFormatter('test1')
    print(df)

    print()
    hf = HexFormatter()
    df.add(hf)
    df.data = 3
    print(df)

    print()
    bf = BinaryFormatter()
    df.add(bf)
    df.data = 21
    print(df)

    print()
    df.remove(hf)
    df.data = 40
    print(df)

    print()
    df.remove(hf)
    df.add(bf)
    df.data = 'hello'
    print(df)

    print()
    df.data = 15.8
    print(df)

if __name__ == '__main__':
    main()


================================================
FILE: chapter14/state.py
================================================
from state_machine import State, Event, acts_as_state_machine, after, before, InvalidStateTransition


@acts_as_state_machine
class Process:
    created = State(initial=True)
    waiting = State()
    running = State()
    terminated = State()
    blocked = State()
    swapped_out_waiting = State()
    swapped_out_blocked = State()

    wait = Event(from_states=(created, running, blocked,
                              swapped_out_waiting), to_state=waiting)
    run = Event(from_states=waiting, to_state=running)
    terminate = Event(from_states=running, to_state=terminated)
    block = Event(from_states=(running, swapped_out_blocked),
                  to_state=blocked)
    swap_wait = Event(from_states=waiting, to_state=swapped_out_waiting)
    swap_block = Event(from_states=blocked, to_state=swapped_out_blocked)

    def __init__(self, name):
        self.name = name

    @after('wait')
    def wait_info(self):
        print('{} entered waiting mode'.format(self.name))

    @after('run')
    def run_info(self):
        print('{} is running'.format(self.name))

    @before('terminate')
    def terminate_info(self):
        print('{} terminated'.format(self.name))

    @after('block')
    def block_info(self):
        print('{} is blocked'.format(self.name))

    @after('swap_wait')
    def swap_wait_info(self):
        print('{} is swapped out and waiting'.format(self.name))

    @after('swap_block')
    def swap_block_info(self):
        print('{} is swapped out and blocked'.format(self.name))


def transition(process, event, event_name):
    try:
        event()
    except InvalidStateTransition as err:
        print('Error: transition of {} from {} to {} failed'.format(process.name,
                                                                    process.current_state, event_name))


def state_info(process):
    print('state of {}: {}'.format(process.name, process.current_state))


def main():
    RUNNING = 'running'
    WAITING = 'waiting'
    BLOCKED = 'blocked'
    TERMINATED = 'terminated'

    p1, p2 = Process('process1'), Process('process2')
    [state_info(p) for p in (p1, p2)]

    print()
    transition(p1, p1.wait, WAITING)
    transition(p2, p2.terminate, TERMINATED)
    [state_info(p) for p in (p1, p2)]

    print()
    transition(p1, p1.run, RUNNING)
    transition(p2, p2.wait, WAITING)
    [state_info(p) for p in (p1, p2)]

    print()
    transition(p2, p2.run, RUNNING)
    [state_info(p) for p in (p1, p2)]

    print()
    [transition(p, p.block, BLOCKED) for p in (p1, p2)]
    [state_info(p) for p in (p1, p2)]

    print()
    [transition(p, p.terminate, TERMINATED) for p in (p1, p2)]
    [state_info(p) for p in (p1, p2)]

if __name__ == '__main__':
    main()


================================================
FILE: chapter15/langs.py
================================================
import pprint
from collections import namedtuple
from operator import attrgetter
if __name__ == '__main__':
    ProgrammingLang = namedtuple('ProgrammingLang', 'name ranking')
    stats = (('Ruby', 14), ('Javascript', 8), ('Python', 7),
             ('Scala', 31), ('Swift', 18), ('Lisp', 23))
    lang_stats = [ProgrammingLang(n, r) for n, r in stats]
    pp = pprint.PrettyPrinter(indent=5)
    pp.pprint(sorted(lang_stats, key=attrgetter('name')))
    print()
    pp.pprint(sorted(lang_stats, key=attrgetter('ranking')))


================================================
FILE: chapter15/strategy.py
================================================
# coding: utf-8

import time
SLOW = 3  # 单位为秒
LIMIT = 5   # 字符数
WARNING = 'too bad, you picked the slow algorithm :('


def pairs(seq):
    n = len(seq)
    for i in range(n):
        yield seq[i], seq[(i + 1) % n]


def allUniqueSort(s):
    if len(s) > LIMIT:
        print(WARNING)
        time.sleep(SLOW)
    srtStr = sorted(s)
    for (c1, c2) in pairs(srtStr):
        if c1 == c2:
            return False
    return True


def allUniqueSet(s):
    if len(s) < LIMIT:
        print(WARNING)
        time.sleep(SLOW)
    return True if len(set(s)) == len(s) else False


def allUnique(s, strategy):
    return strategy(s)


def main():
    while True:
        word = None
        while not word:
            word = input('Insert word (type quit to exit)> ')
            if word == 'quit':
                print('bye')
                return

            strategy_picked = None
            strategies = {'1': allUniqueSet, '2': allUniqueSort}
            while strategy_picked not in strategies.keys():
                strategy_picked = input('Choose strategy: [1] Use a set, [2] Sort and pair> ')

                try:
                    strategy = strategies[strategy_picked]
                    print('allUnique({}): {}'.format(word, allUnique(word, strategy)))
                except KeyError as err:
                    print('Incorrect option: {}'.format(strategy_picked))

if __name__ == '__main__':
    main()


================================================
FILE: chapter16/graph.py
================================================
# coding: utf-8


def bfs(graph, start, end):
    path = []
    visited = [start]
    while visited:
        current = visited.pop(0)
        if current not in path:
            path.append(current)
            if current == end:
                print(path)
                return (True, path)
            # 两个顶点不相连,则跳过
            if current not in graph:
                continue
        visited = visited + graph[current]
    return (False, path)


def dfs(graph, start, end):
    path = []
    visited = [start]
    while visited:
        current = visited.pop(0)
        if current not in path:
            path.append(current)
            if current == end:
                print(path)
                return (True, path)
            # 两个顶点不相连,则跳过
            if current not in graph:
                continue
        visited = graph[current] + visited
    return (False, path)


def main():
    graph = {
        'Frankfurt': ['Mannheim', 'Wurzburg', 'Kassel'],
        'Mannheim': ['Karlsruhe'],
        'Karlsruhe': ['Augsburg'],
        'Augsburg': ['Munchen'],
        'Wurzburg': ['Erfurt', 'Nurnberg'],
        'Nurnberg': ['Stuttgart', 'Munchen'],
        'Kassel': ['Munchen'],
        'Erfurt': [],
        'Stuttgart': [],
        'Munchen': []
    }

    bfs_path = bfs(graph, 'Frankfurt', 'Nurnberg')
    dfs_path = dfs(graph, 'Frankfurt', 'Nurnberg')
    print('bfs Frankfurt-Nurnberg: {}'.format(bfs_path[1] if bfs_path[0] else 'Not found'))
    print('dfs Frankfurt-Nurnberg: {}'.format(dfs_path[1] if dfs_path[0] else 'Not found'))

    bfs_nopath = bfs(graph, 'Wurzburg', 'Kassel')
    print('bfs Wurzburg-Kassel: {}'.format(bfs_nopath[1] if bfs_nopath[0] else 'Not found'))
    dfs_nopath = dfs(graph, 'Wurzburg', 'Kassel')
    print('dfs Wurzburg-Kassel: {}'.format(dfs_nopath[1] if dfs_nopath[0] else 'Not found'))

if __name__ == '__main__':
    main()


================================================
FILE: chapter16/graph_template.py
================================================
# coding: utf-8


def traverse(graph, start, end, action):
    path = []
    visited = [start]
    while visited:
        current = visited.pop(0)
        if current not in path:
            path.append(current)
            if current == end:
                return (True, path)
            # 两个顶点不相连,则跳过
            if current not in graph:
                continue
        visited = action(visited, graph[current])
    return (False, path)


def extend_bfs_path(visited, current):
    return visited + current


def extend_dfs_path(visited, current):
    return current + visited


def main():
    graph = {
        'Frankfurt': ['Mannheim', 'Wurzburg', 'Kassel'],
        'Mannheim': ['Karlsruhe'],
        'Karlsruhe': ['Augsburg'],
        'Augsburg': ['Munchen'],
        'Wurzburg': ['Erfurt', 'Nurnberg'],
        'Nurnberg': ['Stuttgart', 'Munchen'],
        'Kassel': ['Munchen'],
        'Erfurt': [],
        'Stuttgart': [],
        'Munchen': []
    }

    bfs_path = traverse(graph, 'Frankfurt', 'Nurnberg', extend_bfs_path)
    dfs_path = traverse(graph, 'Frankfurt', 'Nurnberg', extend_dfs_path)
    print('bfs Frankfurt-Nurnberg: {}'.format(bfs_path[1] if bfs_path[0] else 'Not found'))
    print('dfs Frankfurt-Nurnberg: {}'.format(dfs_path[1] if dfs_path[0] else 'Not found'))

    bfs_nopath = traverse(graph, 'Wurzburg', 'Kassel', extend_bfs_path)
    print('bfs Wurzburg-Kassel: {}'.format(bfs_nopath[1] if bfs_nopath[0] else 'Not found'))
    dfs_nopath = traverse(graph, 'Wurzburg', 'Kassel', extend_dfs_path)
    print('dfs Wurzburg-Kassel: {}'.format(dfs_nopath[1] if dfs_nopath[0] else 'Not found'))

if __name__ == '__main__':
    main()


================================================
FILE: chapter16/graph_template_slower.py
================================================
# coding: utf-8

BFS = 1
DFS = 2


def traverse(graph, start, end, algorithm):
    path = []
    visited = [start]
    while visited:
        current = visited.pop(0)
        if current not in path:
            path.append(current)
            if current == end:
                return (True, path)
            # 顶点不相连,则跳过
            if current not in graph:
                continue
        if algorithm == BFS:
            visited = extend_bfs_path(visited, graph[current])
        elif algorithm == DFS:
            visited = extend_dfs_path(visited, graph[current])
        else:
            raise ValueError("No such algorithm")
    return (False, path)


def extend_bfs_path(visited, current):
    return visited + current


def extend_dfs_path(visited, current):
    return current + visited


def main():
    graph = {
        'Frankfurt': ['Mannheim', 'Wurzburg', 'Kassel'],
        'Mannheim': ['Karlsruhe'],
        'Karlsruhe': ['Augsburg'],
        'Augsburg': ['Munchen'],
        'Wurzburg': ['Erfurt', 'Nurnberg'],
        'Nurnberg': ['Stuttgart', 'Munchen'],
        'Kassel': ['Munchen'],
        'Erfurt': [],
        'Stuttgart': [],
        'Munchen': []
    }

    bfs_path = traverse(graph, 'Frankfurt', 'Nurnberg', 1)
    dfs_path = traverse(graph, 'Frankfurt', 'Nurnberg', 2)
    print('bfs Frankfurt-Nurnberg: {}'.format(bfs_path[1] if bfs_path[0] else 'Not found'))
    print('dfs Frankfurt-Nurnberg: {}'.format(dfs_path[1] if dfs_path[0] else 'Not found'))

    bfs_nopath = traverse(graph, 'Wurzburg', 'Kassel', 1)
    print('bfs Wurzburg-Kassel: {}'.format(bfs_nopath[1] if bfs_nopath[0] else 'Not found'))
    dfs_nopath = traverse(graph, 'Wurzburg', 'Kassel', 2)
    print('dfs Wurzburg-Kassel: {}'.format(dfs_nopath[1] if dfs_nopath[0] else 'Not found'))

if __name__ == '__main__':
    main()


================================================
FILE: chapter16/template.py
================================================
from cowpy import cow


def dots_style(msg):
    msg = msg.capitalize()
    msg = '.' * 10 + msg + '.' * 10
    return msg


def admire_style(msg):
    msg = msg.upper()
    return '!'.join(msg)


def cow_style(msg):
    msg = cow.milk_random_cow(msg)
    return msg


def generate_banner(msg, style=dots_style):
    print('-- start of banner --')
    print(style(msg))
    print('-- end of banner --\n\n')


def main():
    msg = 'happy coding'
    [generate_banner(msg, style) for style in (dots_style, admire_style, cow_style)]

if __name__ == '__main__':
    main()


================================================
FILE: chapter2/apple-factory.py
================================================
# coding: utf-8

MINI14 = '1.4GHz Mac mini'


class AppleFactory:

    class MacMini14:

        def __init__(self):
            self.memory = 4  # 单位为GB
            self.hdd = 500  # 单位为GB
            self.gpu = 'Intel HD Graphics 5000'

        def __str__(self):
            info = ('Model: {}'.format(MINI14),
                    'Memory: {}GB'.format(self.memory),
                    'Hard Disk: {}GB'.format(self.hdd),
                    'Graphics Card: {}'.format(self.gpu))
            return '\n'.join(info)

    def build_computer(self, model):
        if (model == MINI14):
            return self.MacMini14()
        else:
            print("I dont't know how to build {}".format(model))

if __name__ == '__main__':
    afac = AppleFactory()
    mac_mini = afac.build_computer(MINI14)
    print(mac_mini)


================================================
FILE: chapter2/builder.py
================================================
# coding: utf-8

from enum import Enum
import time

PizzaProgress = Enum('PizzaProgress', 'queued preparation baking ready')
PizzaDough = Enum('PizzaDough', 'thin thick')
PizzaSauce = Enum('PizzaSauce', 'tomato creme_fraiche')
PizzaTopping = Enum('PizzaTopping', 'mozzarella double_mozzarella bacon ham mushrooms red_onion oregano')
STEP_DELAY = 3          # 考虑是示例,单位为秒


class Pizza:

    def __init__(self, name):
        self.name = name
        self.dough = None
        self.sauce = None
        self.topping = []

    def __str__(self):
        return self.name

    def prepare_dough(self, dough):
        self.dough = dough
        print('preparing the {} dough of your {}...'.format(self.dough.name, self))
        time.sleep(STEP_DELAY)
        print('done with the {} dough'.format(self.dough.name))


class MargaritaBuilder:

    def __init__(self):
        self.pizza = Pizza('margarita')
        self.progress = PizzaProgress.queued
        self.baking_time = 5        # 考虑是示例,单位为秒

    def prepare_dough(self):
        self.progress = PizzaProgress.preparation
        self.pizza.prepare_dough(PizzaDough.thin)

    def add_sauce(self):
        print('adding the tomato sauce to your margarita...')
        self.pizza.sauce = PizzaSauce.tomato
        time.sleep(STEP_DELAY)
        print('done with the tomato sauce')

    def add_topping(self):
        print('adding the topping (double mozzarella, oregano) to your margarita')
        self.pizza.topping.append([i for i in
                                   (PizzaTopping.double_mozzarella, PizzaTopping.oregano)])
        time.sleep(STEP_DELAY)
        print('done with the topping (double mozzarrella, oregano)')

    def bake(self):
        self.progress = PizzaProgress.baking
        print('baking your margarita for {} seconds'.format(self.baking_time))
        time.sleep(self.baking_time)
        self.progress = PizzaProgress.ready
        print('your margarita is ready')


class CreamyBaconBuilder:

    def __init__(self):
        self.pizza = Pizza('creamy bacon')
        self.progress = PizzaProgress.queued
        self.baking_time = 7        # 考虑是示例,单位为秒

    def prepare_dough(self):
        self.progress = PizzaProgress.preparation
        self.pizza.prepare_dough(PizzaDough.thick)

    def add_sauce(self):
        print('adding the crème fraîche sauce to your creamy bacon')
        self.pizza.sauce = PizzaSauce.creme_fraiche
        time.sleep(STEP_DELAY)
        print('done with the crème fraîche sauce')

    def add_topping(self):
        print('adding the topping (mozzarella, bacon, ham, mushrooms, red onion, oregano) to your creamy bacon')
        self.pizza.topping.append([t for t in
                                   (PizzaTopping.mozzarella, PizzaTopping.bacon,
                                    PizzaTopping.ham, PizzaTopping.mushrooms,
                                    PizzaTopping.red_onion, PizzaTopping.oregano)])
        time.sleep(STEP_DELAY)
        print('done with the topping (mozzarella, bacon, ham, mushrooms, red onion, oregano)')

    def bake(self):
        self.progress = PizzaProgress.baking
        print('baking your creamy bacon for {} seconds'.format(self.baking_time))
        time.sleep(self.baking_time)
        self.progress = PizzaProgress.ready
        print('your creamy bacon is ready')


class Waiter:

    def __init__(self):
        self.builder = None

    def construct_pizza(self, builder):
        self.builder = builder
        [step() for step in (builder.prepare_dough,
                             builder.add_sauce, builder.add_topping, builder.bake)]

    @property
    def pizza(self):
        return self.builder.pizza


def validate_style(builders):
    try:
        pizza_style = input('What pizza would you like, [m]argarita or [c]reamy bacon? ')
        builder = builders[pizza_style]()
        valid_input = True
    except KeyError as err:
        print('Sorry, only margarita (key m) and creamy bacon (key c) are available')
        return (False, None)
    return (True, builder)


def main():
    builders = dict(m=MargaritaBuilder, c=CreamyBaconBuilder)
    valid_input = False
    while not valid_input:
        valid_input, builder = validate_style(builders)
    print()
    waiter = Waiter()
    waiter.construct_pizza(builder)
    pizza = waiter.pizza
    print()
    print('Enjoy your {}!'.format(pizza))

if __name__ == '__main__':
    main()


================================================
FILE: chapter2/builder2.py
================================================
# coding: utf-8


class Pizza:

    def __init__(self, builder):
        self.garlic = builder.garlic
        self.extra_cheese = builder.extra_cheese

    def __str__(self):
        garlic = 'yes' if self.garlic else 'no'
        cheese = 'yes' if self.extra_cheese else 'no'
        info = ('Garlic: {}'.format(garlic), 'Extra cheese: {}'.format(cheese))
        return '\n'.join(info)

    class PizzaBuilder:

        def __init__(self):
            self.extra_cheese = False
            self.garlic = False

        def add_garlic(self):
            self.garlic = True
            return self

        def add_extra_cheese(self):
            self.extra_cheese = True
            return self

        def build(self):
            return Pizza(self)

if __name__ == '__main__':
    pizza = Pizza.PizzaBuilder().add_garlic().add_extra_cheese().build()
    print(pizza)


================================================
FILE: chapter2/computer-builder.py
================================================
# coding: utf-8


class Computer:

    def __init__(self, serial_number):
        self.serial = serial_number
        self.memory = None      # 单位为GB
        self.hdd = None         # 单位为GB
        self.gpu = None

    def __str__(self):
        info = ('Memory: {}GB'.format(self.memory),
                'Hard Disk: {}GB'.format(self.hdd),
                'Graphics Card: {}'.format(self.gpu))
        return '\n'.join(info)


class ComputerBuilder:

    def __init__(self):
        self.computer = Computer('AG23385193')

    def configure_memory(self, amount):
        self.computer.memory = amount

    def configure_hdd(self, amount):
        self.computer.hdd = amount

    def configure_gpu(self, gpu_model):
        self.computer.gpu = gpu_model


class HardwareEngineer:

    def __init__(self):
        self.builder = None

    def construct_computer(self, memory, hdd, gpu):
        self.builder = ComputerBuilder()
        [step for step in (self.builder.configure_memory(memory),
                           self.builder.configure_hdd(hdd),
                           self.builder.configure_gpu(gpu))]

    @property
    def computer(self):
        return self.builder.computer


def main():
    engineer = HardwareEngineer()
    engineer.construct_computer(hdd=500, memory=8, gpu='GeForce GTX 650 Ti')
    computer = engineer.computer
    print(computer)

if __name__ == '__main__':
    main()


================================================
FILE: chapter3/clone.py
================================================
import copy


class A:

    def __init__(self):
        self.x = 18
        self.msg = 'Hello'


class B(A):

    def __init__(self):
        A.__init__(self)
        self.y = 34

    def __str__(self):
        return '{}, {}, {}'.format(self.x, self.msg, self.y)

if __name__ == '__main__':
    b = B()
    c = copy.deepcopy(b)
    print([str(i) for i in (b, c)])
    print([i for i in (b, c)])


================================================
FILE: chapter3/prototype.py
================================================
# coding: utf-8

import copy
from collections import OrderedDict


class Book:

    def __init__(self, name, authors, price, **rest):
        '''rest的例子有:出版商,长度,标签,出版日期'''
        self.name = name
        self.authors = authors
        self.price = price      # 单位为美元
        self.__dict__.update(rest)

    def __str__(self):
        mylist = []
        ordered = OrderedDict(sorted(self.__dict__.items()))
        for i in ordered.keys():
            mylist.append('{}: {}'.format(i, ordered[i]))
            if i == 'price':
                mylist.append('$')
            mylist.append('\n')
        return ''.join(mylist)


class Prototype:

    def __init__(self):
        self.objects = dict()

    def register(self, identifier, obj):
        self.objects[identifier] = obj

    def unregister(self, identifier):
        del self.objects[identifier]

    def clone(self, identifier, **attr):
        found = self.objects.get(identifier)
        if not found:
            raise ValueError('Incorrect object identifier: {}'.format(identifier))
        obj = copy.deepcopy(found)
        obj.__dict__.update(attr)
        return obj


def main():
    b1 = Book('The C Programming Language', ('Brian W. Kernighan', 'Dennis M.Ritchie'), price=118, publisher='Prentice Hall',
              length=228, publication_date='1978-02-22', tags=('C', 'programming', 'algorithms', 'data structures'))

    prototype = Prototype()
    cid = 'k&r-first'
    prototype.register(cid, b1)
    b2 = prototype.clone(cid, name='The C Programming Language(ANSI)', price=48.99,
                         length=274, publication_date='1988-04-01', edition=2)

    for i in (b1, b2):
        print(i)
    print('ID b1 : {} != ID b2 : {}'.format(id(b1), id(b2)))

if __name__ == '__main__':
    main()


================================================
FILE: chapter4/adapter.py
================================================
from external import Synthesizer, Human


class Computer:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'the {} computer'.format(self.name)

    def execute(self):
        return 'executes a program'


class Adapter:

    def __init__(self, obj, adapted_methods):
        self.obj = obj
        self.__dict__.update(adapted_methods)

    def __str__(self):
        return str(self.obj)


def main():
    objects = [Computer('Asus')]
    synth = Synthesizer('moog')
    objects.append(Adapter(synth, dict(execute=synth.play)))
    human = Human('Bob')
    objects.append(Adapter(human, dict(execute=human.speak)))

    for i in objects:
        print('{} {}'.format(str(i), i.execute()))

if __name__ == "__main__":
    main()


================================================
FILE: chapter4/external.py
================================================
class Synthesizer:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'the {} synthesizer'.format(self.name)

    def play(self):
        return 'is playing an electronic song'


class Human:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return '{} the human'.format(self.name)

    def speak(self):
        return 'says hello'


================================================
FILE: chapter5/mymath.py
================================================
# coding: utf-8

import functools


def memoize(fn):
    known = dict()

    @functools.wraps(fn)
    def memoizer(*args):
        if args not in known:
            known[args] = fn(*args)
        return known[args]

    return memoizer


@memoize
def nsum(n):
    '''返回前n个数字的和'''
    assert(n >= 0), 'n must be >= 0'
    return 0 if n == 0 else n + nsum(n-1)


@memoize
def fibonacci(n):
    '''返回斐波那契数列的第n个数'''
    assert(n >= 0), 'n must be >= 0'
    return n if n in (0, 1) else fibonacci(n-1) + fibonacci(n-2)

if __name__ == '__main__':
    from timeit import Timer
    measure = [{'exec': 'fibonacci(100)', 'import': 'fibonacci',
                'func': fibonacci}, {'exec': 'nsum(200)', 'import': 'nsum',
                                     'func': nsum}]
    for m in measure:
        t = Timer('{}'.format(m['exec']), 'from __main__ import \
            {}'.format(m['import']))
        print('name: {}, doc: {}, executing: {}, time: \
            {}'.format(m['func'].__name__, m['func'].__doc__,
                       m['exec'], t.timeit()))


================================================
FILE: chapter6/facade.py
================================================
# coding: utf-8

from enum import Enum
from abc import ABCMeta, abstractmethod

State = Enum('State', 'new running sleeping restart zombie')


class User:
    pass


class Process:
    pass


class File:
    pass


class Server(metaclass=ABCMeta):

    @abstractmethod
    def __init__(self):
        pass

    def __str__(self):
        return self.name

    @abstractmethod
    def boot(self):
        pass

    @abstractmethod
    def kill(self, restart=True):
        pass


class FileServer(Server):

    def __init__(self):
        '''初始化文件服务进程要求的操作'''
        self.name = 'FileServer'
        self.state = State.new

    def boot(self):
        print('booting the {}'.format(self))
        '''启动文件服务进程要求的操作'''
        self.state = State.running

    def kill(self, restart=True):
        print('Killing {}'.format(self))
        '''杀死文件服务进程要求的操作'''
        self.state = State.restart if restart else State.zombie

    def create_file(self, user, name, permissions):
        '''检查访问权限的有效性、用户权限,等等'''

        print("trying to create the file '{}' for user '{}' with permissions {}".format(name, user, permissions))


class ProcessServer(Server):

    def __init__(self):
        '''初始化进程服务进程要求的操作'''
        self.name = 'ProcessServer'
        self.state = State.new

    def boot(self):
        print('booting the {}'.format(self))
        '''启动进程服务进程要求的操作'''
        self.state = State.running

    def kill(self, restart=True):
        print('Killing {}'.format(self))
        '''杀死进程服务进程要求的操作'''
        self.state = State.restart if restart else State.zombie

    def create_process(self, user, name):
        '''检查用户权限、生成PID,等等'''

        print("trying to create the process '{}' for user '{}'".format(name, user))


class WindowServer:
    pass


class NetworkServer:
    pass


class OperatingSystem:

    '''外观'''

    def __init__(self):
        self.fs = FileServer()
        self.ps = ProcessServer()

    def start(self):
        [i.boot() for i in (self.fs, self.ps)]

    def create_file(self, user, name, permissions):
        return self.fs.create_file(user, name, permissions)

    def create_process(self, user, name):
        return self.ps.create_process(user, name)


def main():
    os = OperatingSystem()
    os.start()
    os.create_file('foo', 'hello', '-rw-r-r')
    os.create_process('bar', 'ls /tmp')

if __name__ == '__main__':
    main()


================================================
FILE: chapter7/flyweight.py
================================================
# coding: utf-8

import random
from enum import Enum

TreeType = Enum('TreeType', 'apple_tree cherry_tree peach_tree')


class Tree:
    pool = dict()

    def __new__(cls, tree_type):
        obj = cls.pool.get(tree_type, None)
        if not obj:
            obj = object.__new__(cls)
            cls.pool[tree_type] = obj
            obj.tree_type = tree_type
        return obj

    def render(self, age, x, y):
        print('render a tree of type {} and age {} at ({}, {})'.format(self.tree_type, age, x, y))


def main():
    rnd = random.Random()
    age_min, age_max = 1, 30    # 单位为年
    min_point, max_point = 0, 100
    tree_counter = 0

    for _ in range(10):
        t1 = Tree(TreeType.apple_tree)
        t1.render(rnd.randint(age_min, age_max),
                  rnd.randint(min_point, max_point),
                  rnd.randint(min_point, max_point))
        tree_counter += 1

    for _ in range(3):
        t2 = Tree(TreeType.cherry_tree)
        t2.render(rnd.randint(age_min, age_max),
                  rnd.randint(min_point, max_point),
                  rnd.randint(min_point, max_point))
        tree_counter += 1

    for _ in range(5):
        t3 = Tree(TreeType.peach_tree)
        t3.render(rnd.randint(age_min, age_max),
                  rnd.randint(min_point, max_point),
                  rnd.randint(min_point, max_point))
        tree_counter += 1

    print('trees rendered: {}'.format(tree_counter))
    print('trees actually created: {}'.format(len(Tree.pool)))

    t4 = Tree(TreeType.cherry_tree)
    t5 = Tree(TreeType.cherry_tree)
    t6 = Tree(TreeType.apple_tree)
    print('{} == {}? {}'.format(id(t4), id(t5), id(t4) == id(t5)))
    print('{} == {}? {}'.format(id(t5), id(t6), id(t5) == id(t6)))

if __name__ == '__main__':
    main()


================================================
FILE: chapter8/mvc.py
================================================
quotes = ('A man is not complete until he is married. Then he is finished.',
          'As I said before, I never repeat myself.',
          'Behind a successful man is an exhausted woman.',
          'Black holes really suck...', 'Facts are stubborn things.')


class QuoteModel:

    def get_quote(self, n):
        try:
            value = quotes[n]
        except IndexError as err:
            value = 'Not found!'
        return value


class QuoteTerminalView:

    def show(self, quote):
        print('And the quote is: "{}"'.format(quote))

    def error(self, msg):
        print('Error: {}'.format(msg))

    def select_quote(self):
        return input('Which quote number would you like to see?')


class QuoteTerminalController:

    def __init__(self):
        self.model = QuoteModel()
        self.view = QuoteTerminalView()

    def run(self):
        valid_input = False
        while not valid_input:
            n = self.view.select_quote()
            try:
                n = int(n)
            except ValueError as err:
                self.view.error("Incorrect index '{}'".format(n))
            else:
                valid_input = True
        quote = self.model.get_quote(n)
        self.view.show(quote)


def main():
    controller = QuoteTerminalController()
    while True:
        controller.run()

if __name__ == '__main__':
    main()


================================================
FILE: chapter9/lazy.py
================================================
# coding: utf-8


class LazyProperty:

    def __init__(self, method):
        self.method = method
        self.method_name = method.__name__
        # print('function overriden: {}'.format(self.method))
        # print("function's name: {}".format(self.method_name))

    def __get__(self, obj, cls):
        if not obj:
            return None
        value = self.method(obj)
        # print('value {}'.format(value))
        setattr(obj, self.method_name, value)
        return value


class Test:

    def __init__(self):
        self.x = 'foo'
        self.y = 'bar'
        self._resource = None

    @LazyProperty
    def resource(self):
        print('initializing self._resource which is: {}'.format(self._resource))
        self._resource = tuple(range(5))    # 代价大的
        return self._resource


def main():
    t = Test()
    print(t.x)
    print(t.y)
    # 做更多的事情。。。
    print(t.resource)
    print(t.resource)

if __name__ == '__main__':
    main()


================================================
FILE: chapter9/proxy.py
================================================
# coding: utf-8


class SensitiveInfo:

    def __init__(self):
        self.users = ['nick', 'tom', 'ben', 'mike']

    def read(self):
        print('There are {} users: {}'.format(len(self.users), ' '.join(self.users)))

    def add(self, user):
        self.users.append(user)
        print('Added user {}'.format(user))


class Info:

    '''SensitiveInfo的保护代理'''

    def __init__(self):
        self.protected = SensitiveInfo()
        self.secret = '0xdeadbeef'

    def read(self):
        self.protected.read()

    def add(self, user):
        sec = input('what is the secret? ')
        self.protected.add(user) if sec == self.secret else print("That's wrong!")


def main():
    info = Info()
    while True:
        print('1. read list |==| 2. add user |==| 3. quit')
        key = input('choose option: ')
        if key == '1':
            info.read()
        elif key == '2':
            name = input('choose username: ')
            info.add(name)
        elif key == '3':
            exit()
        else:
            print('unknown option: {}'.format(key))

if __name__ == '__main__':
    main()
Download .txt
gitextract_hdfimttc/

├── chapter1/
│   ├── abstract_factory.py
│   ├── data/
│   │   ├── donut.json
│   │   └── person.xml
│   ├── factory_method.py
│   └── id.py
├── chapter10/
│   └── chain.py
├── chapter11/
│   ├── command.py
│   └── first-class.py
├── chapter12/
│   └── interpreter.py
├── chapter13/
│   └── observer.py
├── chapter14/
│   └── state.py
├── chapter15/
│   ├── langs.py
│   └── strategy.py
├── chapter16/
│   ├── graph.py
│   ├── graph_template.py
│   ├── graph_template_slower.py
│   └── template.py
├── chapter2/
│   ├── apple-factory.py
│   ├── builder.py
│   ├── builder2.py
│   └── computer-builder.py
├── chapter3/
│   ├── clone.py
│   └── prototype.py
├── chapter4/
│   ├── adapter.py
│   └── external.py
├── chapter5/
│   └── mymath.py
├── chapter6/
│   └── facade.py
├── chapter7/
│   └── flyweight.py
├── chapter8/
│   └── mvc.py
└── chapter9/
    ├── lazy.py
    └── proxy.py
Download .txt
SYMBOL INDEX (294 symbols across 28 files)

FILE: chapter1/abstract_factory.py
  class Frog (line 1) | class Frog:
    method __init__ (line 3) | def __init__(self, name):
    method __str__ (line 6) | def __str__(self):
    method interact_with (line 9) | def interact_with(self, obstacle):
  class Bug (line 14) | class Bug:
    method __str__ (line 16) | def __str__(self):
    method action (line 19) | def action(self):
  class FrogWorld (line 23) | class FrogWorld:
    method __init__ (line 25) | def __init__(self, name):
    method __str__ (line 29) | def __str__(self):
    method make_character (line 32) | def make_character(self):
    method make_obstacle (line 35) | def make_obstacle(self):
  class Wizard (line 39) | class Wizard:
    method __init__ (line 41) | def __init__(self, name):
    method __str__ (line 44) | def __str__(self):
    method interact_with (line 47) | def interact_with(self, obstacle):
  class Ork (line 51) | class Ork:
    method __str__ (line 53) | def __str__(self):
    method action (line 56) | def action(self):
  class WizardWorld (line 60) | class WizardWorld:
    method __init__ (line 62) | def __init__(self, name):
    method __str__ (line 66) | def __str__(self):
    method make_character (line 69) | def make_character(self):
    method make_obstacle (line 72) | def make_obstacle(self):
  class GameEnvironment (line 76) | class GameEnvironment:
    method __init__ (line 78) | def __init__(self, factory):
    method play (line 82) | def play(self):
  function validate_age (line 86) | def validate_age(name):
  function main (line 97) | def main():

FILE: chapter1/factory_method.py
  class JSONConnector (line 5) | class JSONConnector:
    method __init__ (line 7) | def __init__(self, filepath):
    method parsed_data (line 13) | def parsed_data(self):
  class XMLConnector (line 17) | class XMLConnector:
    method __init__ (line 19) | def __init__(self, filepath):
    method parsed_data (line 23) | def parsed_data(self):
  function connection_factory (line 27) | def connection_factory(filepath):
  function connect_to (line 37) | def connect_to(filepath):
  function main (line 46) | def main():

FILE: chapter1/id.py
  class A (line 1) | class A(object):

FILE: chapter10/chain.py
  class Event (line 1) | class Event:
    method __init__ (line 3) | def __init__(self, name):
    method __str__ (line 6) | def __str__(self):
  class Widget (line 10) | class Widget:
    method __init__ (line 12) | def __init__(self, parent=None):
    method handle (line 15) | def handle(self, event):
  class MainWindow (line 26) | class MainWindow(Widget):
    method handle_close (line 28) | def handle_close(self, event):
    method handle_default (line 31) | def handle_default(self, event):
  class SendDialog (line 35) | class SendDialog(Widget):
    method handle_paint (line 37) | def handle_paint(self, event):
  class MsgText (line 41) | class MsgText(Widget):
    method handle_down (line 43) | def handle_down(self, event):
  function main (line 47) | def main():

FILE: chapter11/command.py
  class RenameFile (line 6) | class RenameFile:
    method __init__ (line 8) | def __init__(self, path_src, path_dest):
    method execute (line 11) | def execute(self):
    method undo (line 16) | def undo(self):
  class CreateFile (line 22) | class CreateFile:
    method __init__ (line 24) | def __init__(self, path, txt='hello world\n'):
    method execute (line 27) | def execute(self):
    method undo (line 33) | def undo(self):
  class ReadFile (line 37) | class ReadFile:
    method __init__ (line 39) | def __init__(self, path):
    method execute (line 42) | def execute(self):
  function delete_file (line 49) | def delete_file(path):
  function main (line 55) | def main():

FILE: chapter11/first-class.py
  class RenameFile (line 6) | class RenameFile:
    method __init__ (line 8) | def __init__(self, path_src, path_dest):
    method execute (line 11) | def execute(self):
    method undo (line 16) | def undo(self):
  class CreateFile (line 22) | class CreateFile:
    method __init__ (line 24) | def __init__(self, path, txt='hello world\n'):
    method execute (line 27) | def execute(self):
    method undo (line 33) | def undo(self):
  class ReadFile (line 37) | class ReadFile:
    method __init__ (line 39) | def __init__(self, path):
    method execute (line 42) | def execute(self):
  function delete_file (line 49) | def delete_file(path):
  function main (line 55) | def main():

FILE: chapter12/interpreter.py
  class Gate (line 6) | class Gate:
    method __init__ (line 8) | def __init__(self):
    method __str__ (line 11) | def __str__(self):
    method open (line 14) | def open(self):
    method close (line 18) | def close(self):
  class Garage (line 23) | class Garage:
    method __init__ (line 25) | def __init__(self):
    method __str__ (line 28) | def __str__(self):
    method open (line 31) | def open(self):
    method close (line 35) | def close(self):
  class Aircondition (line 40) | class Aircondition:
    method __init__ (line 42) | def __init__(self):
    method __str__ (line 45) | def __str__(self):
    method turn_on (line 48) | def turn_on(self):
    method turn_off (line 52) | def turn_off(self):
  class Heating (line 57) | class Heating:
    method __init__ (line 59) | def __init__(self):
    method __str__ (line 62) | def __str__(self):
    method turn_on (line 65) | def turn_on(self):
    method turn_off (line 69) | def turn_off(self):
  class Boiler (line 74) | class Boiler:
    method __init__ (line 76) | def __init__(self):
    method __str__ (line 79) | def __str__(self):
    method increase_temperature (line 82) | def increase_temperature(self, amount):
    method decrease_temperature (line 86) | def decrease_temperature(self, amount):
  class Fridge (line 91) | class Fridge:
    method __init__ (line 93) | def __init__(self):
    method __str__ (line 96) | def __str__(self):
    method increase_temperature (line 99) | def increase_temperature(self, amount):
    method decrease_temperature (line 103) | def decrease_temperature(self, amount):
  function main (line 108) | def main():

FILE: chapter13/observer.py
  class Publisher (line 1) | class Publisher:
    method __init__ (line 3) | def __init__(self):
    method add (line 6) | def add(self, observer):
    method remove (line 12) | def remove(self, observer):
    method notify (line 18) | def notify(self):
  class DefaultFormatter (line 22) | class DefaultFormatter(Publisher):
    method __init__ (line 24) | def __init__(self, name):
    method __str__ (line 29) | def __str__(self):
    method data (line 33) | def data(self):
    method data (line 37) | def data(self, new_value):
  class HexFormatter (line 46) | class HexFormatter:
    method notify (line 48) | def notify(self, publisher):
  class BinaryFormatter (line 53) | class BinaryFormatter:
    method notify (line 55) | def notify(self, publisher):
  function main (line 60) | def main():

FILE: chapter14/state.py
  class Process (line 5) | class Process:
    method __init__ (line 23) | def __init__(self, name):
    method wait_info (line 27) | def wait_info(self):
    method run_info (line 31) | def run_info(self):
    method terminate_info (line 35) | def terminate_info(self):
    method block_info (line 39) | def block_info(self):
    method swap_wait_info (line 43) | def swap_wait_info(self):
    method swap_block_info (line 47) | def swap_block_info(self):
  function transition (line 51) | def transition(process, event, event_name):
  function state_info (line 59) | def state_info(process):
  function main (line 63) | def main():

FILE: chapter15/strategy.py
  function pairs (line 9) | def pairs(seq):
  function allUniqueSort (line 15) | def allUniqueSort(s):
  function allUniqueSet (line 26) | def allUniqueSet(s):
  function allUnique (line 33) | def allUnique(s, strategy):
  function main (line 37) | def main():

FILE: chapter16/graph.py
  function bfs (line 4) | def bfs(graph, start, end):
  function dfs (line 21) | def dfs(graph, start, end):
  function main (line 38) | def main():

FILE: chapter16/graph_template.py
  function traverse (line 4) | def traverse(graph, start, end, action):
  function extend_bfs_path (line 20) | def extend_bfs_path(visited, current):
  function extend_dfs_path (line 24) | def extend_dfs_path(visited, current):
  function main (line 28) | def main():

FILE: chapter16/graph_template_slower.py
  function traverse (line 7) | def traverse(graph, start, end, algorithm):
  function extend_bfs_path (line 28) | def extend_bfs_path(visited, current):
  function extend_dfs_path (line 32) | def extend_dfs_path(visited, current):
  function main (line 36) | def main():

FILE: chapter16/template.py
  function dots_style (line 4) | def dots_style(msg):
  function admire_style (line 10) | def admire_style(msg):
  function cow_style (line 15) | def cow_style(msg):
  function generate_banner (line 20) | def generate_banner(msg, style=dots_style):
  function main (line 26) | def main():

FILE: chapter2/apple-factory.py
  class AppleFactory (line 6) | class AppleFactory:
    class MacMini14 (line 8) | class MacMini14:
      method __init__ (line 10) | def __init__(self):
      method __str__ (line 15) | def __str__(self):
    method build_computer (line 22) | def build_computer(self, model):

FILE: chapter2/builder.py
  class Pizza (line 13) | class Pizza:
    method __init__ (line 15) | def __init__(self, name):
    method __str__ (line 21) | def __str__(self):
    method prepare_dough (line 24) | def prepare_dough(self, dough):
  class MargaritaBuilder (line 31) | class MargaritaBuilder:
    method __init__ (line 33) | def __init__(self):
    method prepare_dough (line 38) | def prepare_dough(self):
    method add_sauce (line 42) | def add_sauce(self):
    method add_topping (line 48) | def add_topping(self):
    method bake (line 55) | def bake(self):
  class CreamyBaconBuilder (line 63) | class CreamyBaconBuilder:
    method __init__ (line 65) | def __init__(self):
    method prepare_dough (line 70) | def prepare_dough(self):
    method add_sauce (line 74) | def add_sauce(self):
    method add_topping (line 80) | def add_topping(self):
    method bake (line 89) | def bake(self):
  class Waiter (line 97) | class Waiter:
    method __init__ (line 99) | def __init__(self):
    method construct_pizza (line 102) | def construct_pizza(self, builder):
    method pizza (line 108) | def pizza(self):
  function validate_style (line 112) | def validate_style(builders):
  function main (line 123) | def main():

FILE: chapter2/builder2.py
  class Pizza (line 4) | class Pizza:
    method __init__ (line 6) | def __init__(self, builder):
    method __str__ (line 10) | def __str__(self):
    class PizzaBuilder (line 16) | class PizzaBuilder:
      method __init__ (line 18) | def __init__(self):
      method add_garlic (line 22) | def add_garlic(self):
      method add_extra_cheese (line 26) | def add_extra_cheese(self):
      method build (line 30) | def build(self):

FILE: chapter2/computer-builder.py
  class Computer (line 4) | class Computer:
    method __init__ (line 6) | def __init__(self, serial_number):
    method __str__ (line 12) | def __str__(self):
  class ComputerBuilder (line 19) | class ComputerBuilder:
    method __init__ (line 21) | def __init__(self):
    method configure_memory (line 24) | def configure_memory(self, amount):
    method configure_hdd (line 27) | def configure_hdd(self, amount):
    method configure_gpu (line 30) | def configure_gpu(self, gpu_model):
  class HardwareEngineer (line 34) | class HardwareEngineer:
    method __init__ (line 36) | def __init__(self):
    method construct_computer (line 39) | def construct_computer(self, memory, hdd, gpu):
    method computer (line 46) | def computer(self):
  function main (line 50) | def main():

FILE: chapter3/clone.py
  class A (line 4) | class A:
    method __init__ (line 6) | def __init__(self):
  class B (line 11) | class B(A):
    method __init__ (line 13) | def __init__(self):
    method __str__ (line 17) | def __str__(self):

FILE: chapter3/prototype.py
  class Book (line 7) | class Book:
    method __init__ (line 9) | def __init__(self, name, authors, price, **rest):
    method __str__ (line 16) | def __str__(self):
  class Prototype (line 27) | class Prototype:
    method __init__ (line 29) | def __init__(self):
    method register (line 32) | def register(self, identifier, obj):
    method unregister (line 35) | def unregister(self, identifier):
    method clone (line 38) | def clone(self, identifier, **attr):
  function main (line 47) | def main():

FILE: chapter4/adapter.py
  class Computer (line 4) | class Computer:
    method __init__ (line 6) | def __init__(self, name):
    method __str__ (line 9) | def __str__(self):
    method execute (line 12) | def execute(self):
  class Adapter (line 16) | class Adapter:
    method __init__ (line 18) | def __init__(self, obj, adapted_methods):
    method __str__ (line 22) | def __str__(self):
  function main (line 26) | def main():

FILE: chapter4/external.py
  class Synthesizer (line 1) | class Synthesizer:
    method __init__ (line 3) | def __init__(self, name):
    method __str__ (line 6) | def __str__(self):
    method play (line 9) | def play(self):
  class Human (line 13) | class Human:
    method __init__ (line 15) | def __init__(self, name):
    method __str__ (line 18) | def __str__(self):
    method speak (line 21) | def speak(self):

FILE: chapter5/mymath.py
  function memoize (line 6) | def memoize(fn):
  function nsum (line 19) | def nsum(n):
  function fibonacci (line 26) | def fibonacci(n):

FILE: chapter6/facade.py
  class User (line 9) | class User:
  class Process (line 13) | class Process:
  class File (line 17) | class File:
  class Server (line 21) | class Server(metaclass=ABCMeta):
    method __init__ (line 24) | def __init__(self):
    method __str__ (line 27) | def __str__(self):
    method boot (line 31) | def boot(self):
    method kill (line 35) | def kill(self, restart=True):
  class FileServer (line 39) | class FileServer(Server):
    method __init__ (line 41) | def __init__(self):
    method boot (line 46) | def boot(self):
    method kill (line 51) | def kill(self, restart=True):
    method create_file (line 56) | def create_file(self, user, name, permissions):
  class ProcessServer (line 62) | class ProcessServer(Server):
    method __init__ (line 64) | def __init__(self):
    method boot (line 69) | def boot(self):
    method kill (line 74) | def kill(self, restart=True):
    method create_process (line 79) | def create_process(self, user, name):
  class WindowServer (line 85) | class WindowServer:
  class NetworkServer (line 89) | class NetworkServer:
  class OperatingSystem (line 93) | class OperatingSystem:
    method __init__ (line 97) | def __init__(self):
    method start (line 101) | def start(self):
    method create_file (line 104) | def create_file(self, user, name, permissions):
    method create_process (line 107) | def create_process(self, user, name):
  function main (line 111) | def main():

FILE: chapter7/flyweight.py
  class Tree (line 9) | class Tree:
    method __new__ (line 12) | def __new__(cls, tree_type):
    method render (line 20) | def render(self, age, x, y):
  function main (line 24) | def main():

FILE: chapter8/mvc.py
  class QuoteModel (line 7) | class QuoteModel:
    method get_quote (line 9) | def get_quote(self, n):
  class QuoteTerminalView (line 17) | class QuoteTerminalView:
    method show (line 19) | def show(self, quote):
    method error (line 22) | def error(self, msg):
    method select_quote (line 25) | def select_quote(self):
  class QuoteTerminalController (line 29) | class QuoteTerminalController:
    method __init__ (line 31) | def __init__(self):
    method run (line 35) | def run(self):
  function main (line 49) | def main():

FILE: chapter9/lazy.py
  class LazyProperty (line 4) | class LazyProperty:
    method __init__ (line 6) | def __init__(self, method):
    method __get__ (line 12) | def __get__(self, obj, cls):
  class Test (line 21) | class Test:
    method __init__ (line 23) | def __init__(self):
    method resource (line 29) | def resource(self):
  function main (line 35) | def main():

FILE: chapter9/proxy.py
  class SensitiveInfo (line 4) | class SensitiveInfo:
    method __init__ (line 6) | def __init__(self):
    method read (line 9) | def read(self):
    method add (line 12) | def add(self, user):
  class Info (line 17) | class Info:
    method __init__ (line 21) | def __init__(self):
    method read (line 25) | def read(self):
    method add (line 28) | def add(self, user):
  function main (line 33) | def main():
Condensed preview — 31 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (55K chars).
[
  {
    "path": "chapter1/abstract_factory.py",
    "chars": 2195,
    "preview": "class Frog:\n\n    def __init__(self, name):\n        self.name = name\n\n    def __str__(self):\n        return self.name\n\n  "
  },
  {
    "path": "chapter1/data/donut.json",
    "chars": 2895,
    "preview": "[\n    {\n        \"id\": \"0001\",\n        \"type\": \"donut\",\n        \"name\": \"Cake\",\n        \"ppu\": 0.55,\n        \"batters\": {"
  },
  {
    "path": "chapter1/data/person.xml",
    "chars": 1464,
    "preview": "<persons>\n     <person>\n       <firstName>John</firstName>\n       <lastName>Smith</lastName>\n       <age>25</age>\n      "
  },
  {
    "path": "chapter1/factory_method.py",
    "chars": 1952,
    "preview": "import xml.etree.ElementTree as etree\nimport json\n\n\nclass JSONConnector:\n\n    def __init__(self, filepath):\n        self"
  },
  {
    "path": "chapter1/id.py",
    "chars": 121,
    "preview": "class A(object):\n    pass\n\nif __name__ == '__main__':\n    a = A()\n    b = A()\n\n    print(id(a) == id(b))\n    print(a, b)"
  },
  {
    "path": "chapter10/chain.py",
    "chars": 1398,
    "preview": "class Event:\n\n    def __init__(self, name):\n        self.name = name\n\n    def __str__(self):\n        return self.name\n\n\n"
  },
  {
    "path": "chapter11/command.py",
    "chars": 1778,
    "preview": "import os\n\nverbose = True\n\n\nclass RenameFile:\n\n    def __init__(self, path_src, path_dest):\n        self.src, self.dest "
  },
  {
    "path": "chapter11/first-class.py",
    "chars": 1647,
    "preview": "import os\n\nverbose = True\n\n\nclass RenameFile:\n\n    def __init__(self, path_src, path_dest):\n        self.src, self.dest "
  },
  {
    "path": "chapter12/interpreter.py",
    "chars": 4685,
    "preview": "# coding: utf-8\n\nfrom pyparsing import Word, OneOrMore, Optional, Group, Suppress, alphanums\n\n\nclass Gate:\n\n    def __in"
  },
  {
    "path": "chapter13/observer.py",
    "chars": 1954,
    "preview": "class Publisher:\n\n    def __init__(self):\n        self.observers = []\n\n    def add(self, observer):\n        if observer "
  },
  {
    "path": "chapter14/state.py",
    "chars": 2733,
    "preview": "from state_machine import State, Event, acts_as_state_machine, after, before, InvalidStateTransition\n\n\n@acts_as_state_ma"
  },
  {
    "path": "chapter15/langs.py",
    "chars": 524,
    "preview": "import pprint\nfrom collections import namedtuple\nfrom operator import attrgetter\nif __name__ == '__main__':\n    Programm"
  },
  {
    "path": "chapter15/strategy.py",
    "chars": 1425,
    "preview": "# coding: utf-8\n\nimport time\nSLOW = 3  # 单位为秒\nLIMIT = 5   # 字符数\nWARNING = 'too bad, you picked the slow algorithm :('\n\n\n"
  },
  {
    "path": "chapter16/graph.py",
    "chars": 1881,
    "preview": "# coding: utf-8\n\n\ndef bfs(graph, start, end):\n    path = []\n    visited = [start]\n    while visited:\n        current = v"
  },
  {
    "path": "chapter16/graph_template.py",
    "chars": 1667,
    "preview": "# coding: utf-8\n\n\ndef traverse(graph, start, end, action):\n    path = []\n    visited = [start]\n    while visited:\n      "
  },
  {
    "path": "chapter16/graph_template_slower.py",
    "chars": 1829,
    "preview": "# coding: utf-8\n\nBFS = 1\nDFS = 2\n\n\ndef traverse(graph, start, end, algorithm):\n    path = []\n    visited = [start]\n    w"
  },
  {
    "path": "chapter16/template.py",
    "chars": 570,
    "preview": "from cowpy import cow\n\n\ndef dots_style(msg):\n    msg = msg.capitalize()\n    msg = '.' * 10 + msg + '.' * 10\n    return m"
  },
  {
    "path": "chapter2/apple-factory.py",
    "chars": 819,
    "preview": "# coding: utf-8\n\nMINI14 = '1.4GHz Mac mini'\n\n\nclass AppleFactory:\n\n    class MacMini14:\n\n        def __init__(self):\n   "
  },
  {
    "path": "chapter2/builder.py",
    "chars": 4421,
    "preview": "# coding: utf-8\n\nfrom enum import Enum\nimport time\n\nPizzaProgress = Enum('PizzaProgress', 'queued preparation baking rea"
  },
  {
    "path": "chapter2/builder2.py",
    "chars": 871,
    "preview": "# coding: utf-8\n\n\nclass Pizza:\n\n    def __init__(self, builder):\n        self.garlic = builder.garlic\n        self.extra"
  },
  {
    "path": "chapter2/computer-builder.py",
    "chars": 1408,
    "preview": "# coding: utf-8\n\n\nclass Computer:\n\n    def __init__(self, serial_number):\n        self.serial = serial_number\n        se"
  },
  {
    "path": "chapter3/clone.py",
    "chars": 396,
    "preview": "import copy\n\n\nclass A:\n\n    def __init__(self):\n        self.x = 18\n        self.msg = 'Hello'\n\n\nclass B(A):\n\n    def __"
  },
  {
    "path": "chapter3/prototype.py",
    "chars": 1781,
    "preview": "# coding: utf-8\n\nimport copy\nfrom collections import OrderedDict\n\n\nclass Book:\n\n    def __init__(self, name, authors, pr"
  },
  {
    "path": "chapter4/adapter.py",
    "chars": 775,
    "preview": "from external import Synthesizer, Human\n\n\nclass Computer:\n\n    def __init__(self, name):\n        self.name = name\n\n    d"
  },
  {
    "path": "chapter4/external.py",
    "chars": 414,
    "preview": "class Synthesizer:\n\n    def __init__(self, name):\n        self.name = name\n\n    def __str__(self):\n        return 'the {"
  },
  {
    "path": "chapter5/mymath.py",
    "chars": 1056,
    "preview": "# coding: utf-8\n\nimport functools\n\n\ndef memoize(fn):\n    known = dict()\n\n    @functools.wraps(fn)\n    def memoizer(*args"
  },
  {
    "path": "chapter6/facade.py",
    "chars": 2376,
    "preview": "# coding: utf-8\n\nfrom enum import Enum\nfrom abc import ABCMeta, abstractmethod\n\nState = Enum('State', 'new running sleep"
  },
  {
    "path": "chapter7/flyweight.py",
    "chars": 1781,
    "preview": "# coding: utf-8\n\nimport random\nfrom enum import Enum\n\nTreeType = Enum('TreeType', 'apple_tree cherry_tree peach_tree')\n\n"
  },
  {
    "path": "chapter8/mvc.py",
    "chars": 1371,
    "preview": "quotes = ('A man is not complete until he is married. Then he is finished.',\n          'As I said before, I never repeat"
  },
  {
    "path": "chapter9/lazy.py",
    "chars": 967,
    "preview": "# coding: utf-8\n\n\nclass LazyProperty:\n\n    def __init__(self, method):\n        self.method = method\n        self.method_"
  },
  {
    "path": "chapter9/proxy.py",
    "chars": 1115,
    "preview": "# coding: utf-8\n\n\nclass SensitiveInfo:\n\n    def __init__(self):\n        self.users = ['nick', 'tom', 'ben', 'mike']\n\n   "
  }
]

About this extraction

This page contains the full source code of the youngsterxyf/mpdp-code GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 31 files (49.1 KB), approximately 13.2k tokens, and a symbol index with 294 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!