简体   繁体   English

使用回调满足依赖性的缺点是什么? 而且,这是反模式吗?

[英]What are the drawbacks to using callbacks for satisfying dependencies? And, is this an anti-pattern?

I have two modules: 我有两个模块:

#module_a

def make_a(cb = None):

    global a

    a = 1 # It takes a very long time to make "a", so it is stored as a global in module_a.

    if cb != None:

        cb()

And, 和,

#module_b

import module_a

def make_b():

    global b

    #In order to make "b", we need module_a.a, however there is no guarantee it has been made.
    if 'a' not in dir(module_a):

        module_a.make_a(make_b)

        return

    else:

        b = module_a.a + 1

make_b()

print(b) # 2

In the above code, the function make_b in module_b makes something named b , which depends on something named a in module_a . 在上面的代码中,函数make_bmodule_b使得命名的东西b ,它依赖于一个名为东西amodule_a In order to satisfy its dependency, it calls make_a with a callback to make_b . 为了满足其依赖性,它使用make_a的回调调用make_b Once a is made, then make_b is called again and b is made. 一旦创建a ,则再次调用make_b并生成b

This pattern makes sense to me, but I am wondering if this is a generally accepted approach to doing this or if it is an anti-pattern. 这种模式对我来说很有意义,但是我想知道这是执行此操作的公认方法还是反模式。

Is there a more canonical approach to satisfying such a dependency in Python ie, the Pythonic way? 是否有更规范的方法来满足Python中的这种依赖关系,即Pythonic方式?

To do this in a "Pythonic" way you should introduce an Observer pattern that emits an event once a is computed and b should subscribe to a in order to be called after a is finished. 要以“ Pythonic”方式执行此操作,您应该引入一个Observer模式,该模式一旦计算出a便会发出事件,并且b应当订阅a以便在a完成后被调用。

Here you have an observer example 这里有一个观察者的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python中的BaseBean反模式 - BaseBean anti-pattern in Python 使用 Django ModelField 选择作为字符串的枚举 — 反模式? - Enum using Django ModelField choices as string — anti-pattern? 带有上下文管理器的生成器是反模式吗? - Are generators with context managers an anti-pattern? Python 中的嵌套集和字典是反模式吗? - Are nested sets and dictionaries anti-pattern in Python? Scripts目录是Python中的反模式吗? 如果是这样,进口的正确方法是什么? - Is a Scripts directory an anti-pattern in Python? If so, what's the right way to import? 为什么从同级包中导入模块被视为反模式? - Why is importing a module from a sibling package considered an anti-pattern? 直接在 function 中更改 object 是 python 中的反模式? - Change object directly in function is anti-pattern in python? Python 装饰器采用附加参数反模式 - Python decorator taking additional argument anti-pattern 在 `__enter__` 中返回除 `self` 以外的值是一种反模式吗? - Is returning a value other than `self` in `__enter__` an anti-pattern? 将请求对象发送到Django中的模型方法是否是反模式? - Is it an anti-pattern to send a request object to a model method in Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM