有没有人有关于如何在任何语言中实施lazy()
方法的想法?
示例Python代码可能如下所示:
class A:
def __init__(self):
self.result = ""
pass
def invoke(self):
print("invoke A")
self.result = "RESULT"
def lazy(self):
# I'm not sure how to write this
class B:
def __init__(self, input):
self.input = input
def invoke(self):
print("invoke B: ", self.input)
a = A()
b = B(a.lazy().result) # b needs a reference to the result of `a` before `a` is invoked
a.invoke() # invoke A
b.invoke() # invoke B: RESULT
可以查看更多详细信息here ...
答案:我认为这不是一个糟糕的问题,尽管有人认为是:
我得到了这样的答案:
class Dynamic:
def __init__(self, obj, attr):
self._obj = obj
self._attr = attr
def __str__(self):
return getattr(self._obj, self._attr)
class A:
def __init__(self):
pass
def invoke(self):
print("invoke A")
self.result = "RESULT"
class B:
def __init__(self, input):
self.input = input
def invoke(self):
print("invoke B: ", self.input)
a = A()
b = B(Dynamic(a, "result"))
a.invoke() # invoke A
b.invoke() # invoke B: RESULT
答案 0 :(得分:1)
不确定我是否正确......这样的事情?
class A:
def __init__(self):
self.result = ""
def invoke(self):
print("invoke A")
self.result = "RESULT"
def lazy(self):
return self.result
class B:
def __init__(self, input):
self.input = input
def invoke(self):
print("invoke B: ", self.input())
a = A()
b = B(a.lazy) # b needs a reference to the result of `a` before `a` is invoked
a.invoke() # invoke A
b.invoke() # invoke B: RESULT