【发布时间】:2026-02-10 00:50:02
【问题描述】:
我在同一个类中实现了一些逻辑进程。
类实例为每个进程获取一个生成器,run() 推进所述生成器。在我的情况下,生成器不会结束。
你会如何在下面的代码中调用 foo_function 和 foo_object
class C(threading.Thread):
def foo_function(self):
""" generator *function*,
logical process foo """
while True:
# some state checks
if self.some_attr:
# side-effects here
pass
yield
def __init__(self):
# generator *object*
# i.e. process instance
self.foo_object = self.foo_function() # <- here
def run(self):
while True:
next(self.foo_object)
next(self.another_object)
if xxx:
next(self.yet_another_object)
典型流程为discovery、authentication、watchdog等
如何以合理的方式命名定义生成器的函数和包含生成器对象的属性?
最后只是为了好玩,同名的名字会很疯狂,对吧?
class C:
def foo(self):
yield 1; yield 2
def __init__(self):
self.foo = self.foo()
c = C()
type(C.foo) is function
type(c.foo) is generator
【问题讨论】:
-
小伙子们,你们发表评论怎么样?毕竟它处理martinfowler.com/bliki/TwoHardThings.html :)
-
正如所写,是的,这很令人困惑。 :) 你有一些具体的细节可能有助于澄清这个非常抽象的例子吗?详细信息: foo() 纯粹是为了副作用而运行? self.maybe_foo = foo_if_some_attr()
-
你真的把我弄丢了:self.name_me_process_generator = self.name_me_process_function()
-
好点,我会尝试重新编辑。
标签: python naming-conventions generator naming lightweight-processes