如何使用 lambda 创建基于工厂的方法?
函数签名看起来像这样。 Factory 获取字符串参数并返回实例。
class Foo:
@abstractmethod
def store(factory: Callable[[str], Bar])
obj = factory("abc") // store or call to get instance
class Bar:
def __init__(self):
pass
如何使用lambda调用这个方法?
Foo.store(lambda k: Bar(k))
错误
参数“工厂”未填写
由于
store()
是在类上调用的,而不是实例上,因此需要将其声明为静态方法。
class Foo:
@staticmethod
def store(factory: Callable[[str], Bar])
obj = factory("abc") // store or call to get instance
否则,预计会在实例上调用它,并且第一个参数应该是
self
,它接收实例。