在Python代码中,这里是使用依赖注入的合适地方吗?如果是,怎么做?
代码的设置如下:
- 模块 ui_theme.py 定义了一个主题和变体选择器。
- variant_selector 有一个 on_change 事件处理器。
- 模块 cards_page.py 导入了 ui_theme.py,并且有一个处理 on_variant_change 的函数。
现在,我想实现的是,当 ui_theme 的 on_change 事件被触发时,它应该以某种方式调用 cards_page 的 on_variant_change 事件。
限制条件:我绝对不想创建一个函数来生成 variant_selector。这样会让代码变得有点乱。我也不能在初始化后设置事件处理器。
我目前的解决方案如下:
- 在 ui_theme.py 中
on_change_variant_callback = None
def on_change_variant_click(dbref, msg, to_ms):
print ("button clicked:", msg.value)
if on_change_variant_callback:
on_change_variant_callback(dbref, msg, to_ms)
pass
- 在 cards.py 中
import ui_theme
def on_variant_select():
pass
ui_theme.on_change_variant_callback = on_variant_select
我觉得应该有更好的方法——可能依赖注入可以帮忙,尽管我对这个概念还不太理解。
2 个回答
0
通过使用依赖注入,你可以让你的代码变得更加模块化和灵活。简单来说,就是你把一个对象需要的组件从外部提供给它。这样一来,你就可以减少模块之间的紧密关系,让代码更容易管理,也更能适应未来的变化。
在你现在的情况中,你在ui_theme.py文件中定义了一个叫做on_change_variant_callback的函数,并在cards_page.py文件中给这个回调函数赋了值。这就导致了这两个文件之间的关系非常紧密。
我们可以通过依赖注入来减轻这种紧密关系。也就是说,我们可以以某种方式将on_change_variant_callback函数从外部传递给ui_theme.py模块。这样一来,就减少了ui_theme.py和cards_page.py文件之间的依赖关系,让我们的代码结构更加模块化和灵活。
使用这种方法,你可以更容易地适应未来代码的发展,也能轻松应对可能的变化。
ui_theme.py
class VariantSelector:
def __init__(self, on_change_callback=None):
self.on_change_callback = on_change_callback
def on_change_variant_click(self, dbref, msg, to_ms):
print("button clicked:", msg.value)
if self.on_change_callback:
self.on_change_callback(dbref, msg, to_ms)
cards_page.py
from ui_theme import VariantSelector
def on_variant_select(dbref, msg, to_ms):
# Handle the variant change event
pass
variant_selector = VariantSelector(on_change_callback=on_variant_select)
0
你可以创建一个监听器,并在CardsPage类中初始化它。
# ui_theme.py
class ThemeVariantListener:
def __init__(self):
self.on_change_variant_callback = None
def set_variant_change_callback(self, callback):
self.on_change_variant_callback = callback
def on_change_variant_click(self, dbref, msg, to_ms):
print("button clicked:", msg.value)
if self.on_change_variant_callback:
self.on_change_variant_callback(dbref, msg, to_ms)
# cards_page.py
import ui_theme
class CardsPage:
def __init__(self):
self.theme_listener = ui_theme.ThemeVariantListener()
def on_variant_select(self, dbref, msg, to_ms):
# Your logic for variant selection
pass
def initialize(self):
self.theme_listener.set_variant_change_callback(self.on_variant_select)
# main.py
from cards_page import CardsPage
def main():
cards_page = CardsPage()
cards_page.initialize()
# Now, you can use ui_theme.py and set its variant change callback
ui_theme_instance = cards_page.theme_listener
# Here, you can pass ui_theme_instance to wherever needed in your application
# For example:
# some_module.setup_ui_theme(ui_theme_instance)
if __name__ == "__main__":
main()