{"id":10021257,"date":"2026-02-19T12:38:29","date_gmt":"2026-02-19T04:38:29","guid":{"rendered":"https:\/\/itmax.cn\/?p=10021257"},"modified":"2026-02-19T12:38:29","modified_gmt":"2026-02-19T04:38:29","slug":"%e5%a4%a7%e5%9e%8b-python-%e9%a1%b9%e7%9b%ae%e6%9e%b6%e6%9e%84%ef%bc%9a%e6%a8%a1%e5%9d%97%e5%8c%96%e4%b8%8e%e4%be%9d%e8%b5%96%e6%b3%a8%e5%85%a5%e5%ae%9e%e8%b7%b5","status":"publish","type":"post","link":"https:\/\/itmax.cn\/?p=10021257","title":{"rendered":"\u5927\u578b Python \u9879\u76ee\u67b6\u6784\uff1a\u6a21\u5757\u5316\u4e0e\u4f9d\u8d56\u6ce8\u5165\u5b9e\u8df5"},"content":{"rendered":"<h2>\u5927\u578b Python \u9879\u76ee\u67b6\u6784\uff1a\u6a21\u5757\u5316\u4e0e\u4f9d\u8d56\u6ce8\u5165\u5b9e\u8df5<\/h2>\n<p>\u5927\u578b Python \u9879\u76ee\u7684\u67b6\u6784\u8bbe\u8ba1\u9700\u8981\u8003\u8651\u53ef\u7ef4\u62a4\u6027\u3001\u53ef\u6269\u5c55\u6027\u548c\u53ef\u6d4b\u8bd5\u6027\u3002\u672c\u6587\u5c06\u6df1\u5165\u63a2\u8ba8\u5927\u578b\u9879\u76ee\u7684\u6a21\u5757\u5316\u8bbe\u8ba1\u548c\u4f9d\u8d56\u6ce8\u5165\u5b9e\u8df5\uff0c\u5e2e\u52a9\u8bfb\u8005\u6784\u5efa\u5065\u58ee\u3001\u7075\u6d3b\u7684 Python \u5e94\u7528\u67b6\u6784\u3002<\/p>\n<h3>\u6a21\u5757\u5316\u8bbe\u8ba1\u539f\u5219<\/h3>\n<p>\u6a21\u5757\u5316\u8bbe\u8ba1\u662f\u5927\u578b\u9879\u76ee\u67b6\u6784\u7684\u57fa\u7840\uff0c\u5b83\u5c06\u590d\u6742\u7cfb\u7edf\u5206\u89e3\u4e3a\u53ef\u7ba1\u7406\u7684\u6a21\u5757\u3002<\/p>\n<pre><code class=\"python\">class Module:\n    def __init__(self, name):\n        self.name = name\n        self.dependencies = []\n    \n    def add_dependency(self, module):\n        self.dependencies.append(module)\n    \n    def initialize(self):\n        print(f&quot;\u521d\u59cb\u5316\u6a21\u5757: {self.name}&quot;)\n        for dep in self.dependencies:\n            dep.initialize()\n\ndef modular_design_demo():\n    print(&quot;\u6a21\u5757\u5316\u8bbe\u8ba1\u6f14\u793a:&quot;)\n    \n    database_module = Module(&quot;\u6570\u636e\u5e93\u6a21\u5757&quot;)\n    auth_module = Module(&quot;\u8ba4\u8bc1\u6a21\u5757&quot;)\n    api_module = Module(&quot;API \u6a21\u5757&quot;)\n    \n    api_module.add_dependency(database_module)\n    api_module.add_dependency(auth_module)\n    \n    api_module.initialize()\n\nmodular_design_demo()<\/code><\/pre>\n<h3>\u5206\u5c42\u67b6\u6784<\/h3>\n<p>\u5206\u5c42\u67b6\u6784\u5c06\u7cfb\u7edf\u6309\u804c\u8d23\u5212\u5206\u4e3a\u4e0d\u540c\u7684\u5c42\u6b21\uff0c\u6bcf\u5c42\u53ea\u4e0e\u76f8\u90bb\u5c42\u4ea4\u4e92\u3002<\/p>\n<pre><code class=\"python\">class DataLayer:\n    def save(self, data):\n        print(f&quot;\u4fdd\u5b58\u6570\u636e: {data}&quot;)\n        return True\n\nclass BusinessLayer:\n    def __init__(self, data_layer):\n        self.data_layer = data_layer\n    \n    def process(self, data):\n        processed_data = f&quot;\u5904\u7406\u540e\u7684 {data}&quot;\n        return self.data_layer.save(processed_data)\n\nclass PresentationLayer:\n    def __init__(self, business_layer):\n        self.business_layer = business_layer\n    \n    def handle_request(self, request):\n        return self.business_layer.process(request)\n\ndef layered_architecture_demo():\n    print(&quot;\u5206\u5c42\u67b6\u6784\u6f14\u793a:&quot;)\n    \n    data_layer = DataLayer()\n    business_layer = BusinessLayer(data_layer)\n    presentation_layer = PresentationLayer(business_layer)\n    \n    result = presentation_layer.handle_request(&quot;\u7528\u6237\u6570\u636e&quot;)\n    print(f&quot;\u5904\u7406\u7ed3\u679c: {result}&quot;)\n\nlayered_architecture_demo()<\/code><\/pre>\n<h3>\u4f9d\u8d56\u6ce8\u5165\u57fa\u7840<\/h3>\n<p>\u4f9d\u8d56\u6ce8\u5165\u662f\u4e00\u79cd\u5b9e\u73b0\u63a7\u5236\u53cd\u8f6c\u7684\u6280\u672f\uff0c\u5b83\u5c06\u4f9d\u8d56\u5bf9\u8c61\u7684\u521b\u5efa\u548c\u4f7f\u7528\u5206\u79bb\u3002<\/p>\n<pre><code class=\"python\">class Database:\n    def query(self, sql):\n        return f&quot;\u67e5\u8be2\u7ed3\u679c: {sql}&quot;\n\nclass Service:\n    def __init__(self, database):\n        self.database = database\n    \n    def get_data(self):\n        return self.database.query(&quot;SELECT * FROM users&quot;)\n\ndef dependency_injection_demo():\n    print(&quot;\u4f9d\u8d56\u6ce8\u5165\u6f14\u793a:&quot;)\n    \n    database = Database()\n    service = Service(database)\n    \n    result = service.get_data()\n    print(result)\n\ndependency_injection_demo()<\/code><\/pre>\n<h3>\u4f9d\u8d56\u6ce8\u5165\u5bb9\u5668<\/h3>\n<p>\u4f9d\u8d56\u6ce8\u5165\u5bb9\u5668\u8d1f\u8d23\u7ba1\u7406\u548c\u89e3\u6790\u4f9d\u8d56\u5173\u7cfb\u3002<\/p>\n<pre><code class=\"python\">class Container:\n    def __init__(self):\n        self._services = {}\n        self._factories = {}\n    \n    def register(self, name, factory):\n        self._factories[name] = factory\n    \n    def get(self, name):\n        if name not in self._services:\n            self._services[name] = self._factories[name](self)\n        return self._services[name]\n\ndef container_demo():\n    print(&quot;\u4f9d\u8d56\u6ce8\u5165\u5bb9\u5668\u6f14\u793a:&quot;)\n    \n    container = Container()\n    \n    container.register('database', lambda c: Database())\n    container.register('service', lambda c: Service(c.get('database')))\n    \n    service = container.get('service')\n    result = service.get_data()\n    print(result)\n\ncontainer_demo()<\/code><\/pre>\n<h3>\u9879\u76ee\u67b6\u6784\u8bbe\u8ba1<\/h3>\n<pre style=\"display:none;\"><code class=\"mermaid\">graph TD\n    A[\u8868\u793a\u5c42] --&gt; B[\u4e1a\u52a1\u903b\u8f91\u5c42]\n    B --&gt; C[\u6570\u636e\u8bbf\u95ee\u5c42]\n    C --&gt; D[\u6570\u636e\u5e93]\n    B --&gt; E[\u670d\u52a1\u5c42]\n    E --&gt; F[\u5916\u90e8\u670d\u52a1]\n    G[\u4f9d\u8d56\u6ce8\u5165\u5bb9\u5668] --&gt; A\n    G --&gt; B\n    G --&gt; C\n    G --&gt; E<\/code><\/pre>\n<h3>\u6a21\u5757\u901a\u4fe1\u673a\u5236<\/h3>\n<p>\u6a21\u5757\u95f4\u7684\u901a\u4fe1\u673a\u5236\u51b3\u5b9a\u4e86\u7cfb\u7edf\u7684\u8026\u5408\u5ea6\u548c\u53ef\u7ef4\u62a4\u6027\u3002<\/p>\n<pre><code class=\"python\">class EventBus:\n    def __init__(self):\n        self._subscribers = {}\n    \n    def subscribe(self, event_type, handler):\n        if event_type not in self._subscribers:\n            self._subscribers[event_type] = []\n        self._subscribers[event_type].append(handler)\n    \n    def publish(self, event_type, data):\n        if event_type in self._subscribers:\n            for handler in self._subscribers[event_type]:\n                handler(data)\n\ndef event_bus_demo():\n    print(&quot;\u4e8b\u4ef6\u603b\u7ebf\u6f14\u793a:&quot;)\n    \n    event_bus = EventBus()\n    \n    def handler1(data):\n        print(f&quot;\u5904\u7406\u56681\u6536\u5230: {data}&quot;)\n    \n    def handler2(data):\n        print(f&quot;\u5904\u7406\u56682\u6536\u5230: {data}&quot;)\n    \n    event_bus.subscribe(&quot;user_created&quot;, handler1)\n    event_bus.subscribe(&quot;user_created&quot;, handler2)\n    \n    event_bus.publish(&quot;user_created&quot;, {&quot;name&quot;: &quot;\u5f20\u4e09&quot;})\n\nevent_bus_demo()<\/code><\/pre>\n<h3>\u914d\u7f6e\u7ba1\u7406<\/h3>\n<p>\u914d\u7f6e\u7ba1\u7406\u662f\u5927\u578b\u9879\u76ee\u7684\u91cd\u8981\u7ec4\u6210\u90e8\u5206\u3002<\/p>\n<pre><code class=\"python\">class Config:\n    def __init__(self):\n        self._config = {}\n    \n    def set(self, key, value):\n        self._config[key] = value\n    \n    def get(self, key, default=None):\n        return self._config.get(key, default)\n    \n    def load_from_dict(self, config_dict):\n        self._config.update(config_dict)\n\ndef config_management_demo():\n    print(&quot;\u914d\u7f6e\u7ba1\u7406\u6f14\u793a:&quot;)\n    \n    config = Config()\n    config.load_from_dict({\n        &quot;database&quot;: {\n            &quot;host&quot;: &quot;localhost&quot;,\n            &quot;port&quot;: 5432\n        },\n        &quot;debug&quot;: True\n    })\n    \n    print(f&quot;\u6570\u636e\u5e93\u4e3b\u673a: {config.get('database', {}).get('host')}&quot;)\n    print(f&quot;\u8c03\u8bd5\u6a21\u5f0f: {config.get('debug')}&quot;)\n\nconfig_management_demo()<\/code><\/pre>\n<h3>\u63d2\u4ef6\u7cfb\u7edf<\/h3>\n<p>\u63d2\u4ef6\u7cfb\u7edf\u63d0\u4f9b\u4e86\u7075\u6d3b\u7684\u6269\u5c55\u673a\u5236\u3002<\/p>\n<pre><code class=\"python\">class Plugin:\n    def initialize(self):\n        pass\n    \n    def execute(self, data):\n        pass\n\nclass PluginManager:\n    def __init__(self):\n        self._plugins = []\n    \n    def register_plugin(self, plugin):\n        self._plugins.append(plugin)\n        plugin.initialize()\n    \n    def execute_all(self, data):\n        results = []\n        for plugin in self._plugins:\n            result = plugin.execute(data)\n            results.append(result)\n        return results\n\ndef plugin_system_demo():\n    print(&quot;\u63d2\u4ef6\u7cfb\u7edf\u6f14\u793a:&quot;)\n    \n    class LoggingPlugin(Plugin):\n        def initialize(self):\n            print(&quot;\u65e5\u5fd7\u63d2\u4ef6\u521d\u59cb\u5316&quot;)\n        \n        def execute(self, data):\n            print(f&quot;\u8bb0\u5f55\u65e5\u5fd7: {data}&quot;)\n            return data\n    \n    class ValidationPlugin(Plugin):\n        def initialize(self):\n            print(&quot;\u9a8c\u8bc1\u63d2\u4ef6\u521d\u59cb\u5316&quot;)\n        \n        def execute(self, data):\n            print(f&quot;\u9a8c\u8bc1\u6570\u636e: {data}&quot;)\n            return data\n    \n    manager = PluginManager()\n    manager.register_plugin(LoggingPlugin())\n    manager.register_plugin(ValidationPlugin())\n    \n    manager.execute_all({&quot;name&quot;: &quot;\u6d4b\u8bd5\u6570\u636e&quot;})\n\nplugin_system_demo()<\/code><\/pre>\n<h3>\u4e2d\u95f4\u4ef6\u6a21\u5f0f<\/h3>\n<p>\u4e2d\u95f4\u4ef6\u6a21\u5f0f\u63d0\u4f9b\u4e86\u8bf7\u6c42\u5904\u7406\u7684\u6269\u5c55\u70b9\u3002<\/p>\n<pre><code class=\"python\">class Middleware:\n    def __init__(self):\n        self.next_middleware = None\n    \n    def set_next(self, middleware):\n        self.next_middleware = middleware\n        return middleware\n    \n    def handle(self, request):\n        if self.next_middleware:\n            return self.next_middleware.handle(request)\n        return request\n\nclass LoggingMiddleware(Middleware):\n    def handle(self, request):\n        print(f&quot;\u65e5\u5fd7\u4e2d\u95f4\u4ef6: {request}&quot;)\n        return super().handle(request)\n\nclass AuthMiddleware(Middleware):\n    def handle(self, request):\n        print(f&quot;\u8ba4\u8bc1\u4e2d\u95f4\u4ef6: {request}&quot;)\n        return super().handle(request)\n\ndef middleware_pattern_demo():\n    print(&quot;\u4e2d\u95f4\u4ef6\u6a21\u5f0f\u6f14\u793a:&quot;)\n    \n    logging = LoggingMiddleware()\n    auth = AuthMiddleware()\n    \n    logging.set_next(auth)\n    result = logging.handle({&quot;user&quot;: &quot;admin&quot;})\n    print(f&quot;\u6700\u7ec8\u7ed3\u679c: {result}&quot;)\n\nmiddleware_pattern_demo()<\/code><\/pre>\n<h3>\u670d\u52a1\u53d1\u73b0<\/h3>\n<p>\u670d\u52a1\u53d1\u73b0\u673a\u5236\u652f\u6301\u52a8\u6001\u670d\u52a1\u6ce8\u518c\u548c\u67e5\u627e\u3002<\/p>\n<pre><code class=\"python\">class ServiceRegistry:\n    def __init__(self):\n        self._services = {}\n    \n    def register(self, name, address):\n        if name not in self._services:\n            self._services[name] = []\n        self._services[name].append(address)\n    \n    def discover(self, name):\n        return self._services.get(name, [])\n\ndef service_discovery_demo():\n    print(&quot;\u670d\u52a1\u53d1\u73b0\u6f14\u793a:&quot;)\n    \n    registry = ServiceRegistry()\n    \n    registry.register(&quot;user-service&quot;, &quot;localhost:8001&quot;)\n    registry.register(&quot;user-service&quot;, &quot;localhost:8002&quot;)\n    registry.register(&quot;order-service&quot;, &quot;localhost:8003&quot;)\n    \n    user_services = registry.discover(&quot;user-service&quot;)\n    print(f&quot;\u7528\u6237\u670d\u52a1: {user_services}&quot;)\n    \n    order_services = registry.discover(&quot;order-service&quot;)\n    print(f&quot;\u8ba2\u5355\u670d\u52a1: {order_services}&quot;)\n\nservice_discovery_demo()<\/code><\/pre>\n<h3>\u9519\u8bef\u5904\u7406<\/h3>\n<p>\u7edf\u4e00\u7684\u9519\u8bef\u5904\u7406\u673a\u5236\u63d0\u9ad8\u4e86\u7cfb\u7edf\u7684\u5065\u58ee\u6027\u3002<\/p>\n<pre><code class=\"python\">class ErrorHandler:\n    def __init__(self):\n        self._handlers = {}\n    \n    def register_handler(self, exception_type, handler):\n        self._handlers[exception_type] = handler\n    \n    def handle(self, exception):\n        exception_type = type(exception)\n        if exception_type in self._handlers:\n            return self._handlers[exception_type](exception)\n        return f&quot;\u672a\u5904\u7406\u7684\u5f02\u5e38: {exception}&quot;\n\ndef error_handling_demo():\n    print(&quot;\u9519\u8bef\u5904\u7406\u6f14\u793a:&quot;)\n    \n    handler = ErrorHandler()\n    \n    def handle_value_error(e):\n        return f&quot;\u503c\u9519\u8bef: {e}&quot;\n    \n    def handle_key_error(e):\n        return f&quot;\u952e\u9519\u8bef: {e}&quot;\n    \n    handler.register_handler(ValueError, handle_value_error)\n    handler.register_handler(KeyError, handle_key_error)\n    \n    print(handler.handle(ValueError(&quot;\u65e0\u6548\u7684\u503c&quot;)))\n    print(handler.handle(KeyError(&quot;\u672a\u627e\u5230\u952e&quot;)))\n\nerror_handling_demo()<\/code><\/pre>\n<h3>\u65e5\u5fd7\u7cfb\u7edf<\/h3>\n<p>\u5b8c\u5584\u7684\u65e5\u5fd7\u7cfb\u7edf\u5bf9\u4e8e\u5927\u578b\u9879\u76ee\u7684\u8c03\u8bd5\u548c\u76d1\u63a7\u81f3\u5173\u91cd\u8981\u3002<\/p>\n<pre><code class=\"python\">import logging\nfrom logging.handlers import RotatingFileHandler\n\nclass Logger:\n    def __init__(self, name, log_file):\n        self.logger = logging.getLogger(name)\n        self.logger.setLevel(logging.INFO)\n        \n        handler = RotatingFileHandler(log_file, maxBytes=1024*1024, backupCount=5)\n        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n        handler.setFormatter(formatter)\n        \n        self.logger.addHandler(handler)\n    \n    def info(self, message):\n        self.logger.info(message)\n    \n    def error(self, message):\n        self.logger.error(message)\n\ndef logging_system_demo():\n    print(&quot;\u65e5\u5fd7\u7cfb\u7edf\u6f14\u793a:&quot;)\n    \n    logger = Logger(&quot;app&quot;, &quot;app.log&quot;)\n    logger.info(&quot;\u5e94\u7528\u542f\u52a8&quot;)\n    logger.error(&quot;\u53d1\u751f\u9519\u8bef&quot;)\n    \n    print(&quot;\u65e5\u5fd7\u5df2\u8bb0\u5f55\u5230 app.log&quot;)\n\nlogging_system_demo()<\/code><\/pre>\n<h3>\u6d4b\u8bd5\u7b56\u7565<\/h3>\n<p>\u5168\u9762\u7684\u6d4b\u8bd5\u7b56\u7565\u786e\u4fdd\u4e86\u7cfb\u7edf\u7684\u8d28\u91cf\u3002<\/p>\n<pre><code class=\"python\">import unittest\n\nclass Calculator:\n    def add(self, a, b):\n        return a + b\n    \n    def subtract(self, a, b):\n        return a - b\n\nclass TestCalculator(unittest.TestCase):\n    def setUp(self):\n        self.calculator = Calculator()\n    \n    def test_add(self):\n        self.assertEqual(self.calculator.add(2, 3), 5)\n    \n    def test_subtract(self):\n        self.assertEqual(self.calculator.subtract(5, 3), 2)\n\ndef testing_strategy_demo():\n    print(&quot;\u6d4b\u8bd5\u7b56\u7565\u6f14\u793a:&quot;)\n    \n    suite = unittest.TestLoader().loadTestsFromTestCase(TestCalculator)\n    runner = unittest.TextTestRunner(verbosity=2)\n    runner.run(suite)\n\ntesting_strategy_demo()<\/code><\/pre>\n<h3>\u603b\u7ed3<\/h3>\n<p>\u5927\u578b Python \u9879\u76ee\u7684\u67b6\u6784\u8bbe\u8ba1\u9700\u8981\u7efc\u5408\u8003\u8651\u6a21\u5757\u5316\u3001\u4f9d\u8d56\u6ce8\u5165\u3001\u5206\u5c42\u67b6\u6784\u7b49\u591a\u4e2a\u65b9\u9762\u3002\u901a\u8fc7\u5408\u7406\u7684\u8bbe\u8ba1\u6a21\u5f0f\u548c\u5b9e\u8df5\uff0c\u6211\u4eec\u53ef\u4ee5\u6784\u5efa\u51fa\u53ef\u7ef4\u62a4\u3001\u53ef\u6269\u5c55\u3001\u53ef\u6d4b\u8bd5\u7684\u5927\u578b\u5e94\u7528\u7cfb\u7edf\u3002<\/p>\n<p>\u638c\u63e1\u8fd9\u4e9b\u67b6\u6784\u8bbe\u8ba1\u539f\u5219\u548c\u5b9e\u8df5\uff0c\u5bf9\u4e8e\u5f00\u53d1\u9ad8\u8d28\u91cf\u7684 Python \u5e94\u7528\u81f3\u5173\u91cd\u8981\u3002\u5728\u5b9e\u9645\u9879\u76ee\u4e2d\uff0c\u9700\u8981\u6839\u636e\u5177\u4f53\u7684\u4e1a\u52a1\u9700\u6c42\u548c\u6280\u672f\u7ea6\u675f\uff0c\u7075\u6d3b\u5e94\u7528\u8fd9\u4e9b\u8bbe\u8ba1\u7406\u5ff5\u3002<\/p>\n<p><a href=\"https:\/\/segmentfault.com\/a\/1190000047614283\">https:\/\/segmentfault.com\/a\/1190000047614283<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5927\u578b Python \u9879\u76ee\u67b6\u6784\uff1a\u6a21\u5757\u5316\u4e0e\u4f9d\u8d56\u6ce8\u5165\u5b9e\u8df5 \u5927\u578b Python \u9879\u76ee\u7684\u67b6\u6784\u8bbe\u8ba1\u9700\u8981\u8003\u8651\u53ef\u7ef4\u62a4\u6027\u3001\u53ef\u6269\u5c55 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[4],"tags":[],"class_list":["post-10021257","post","type-post","status-publish","format-standard","hentry","category-share"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021257","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10021257"}],"version-history":[{"count":0,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10021257\/revisions"}],"wp:attachment":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10021257"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10021257"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10021257"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}