我有2個模塊,每個模塊都包含一個類。
我的主程序實例化了一個類的對象,它實例化了許多類的對象。
我需要能夠從第二類的實例中調用第一類函數。
這是什麼,我有一個大致的樣子:如何在python中調用實例創建者的函數?
模塊mod_one.py:
import mod_two
class One:
def __init__(self):
self.new_instance = Two()
def call_back_func(self):
# This function should be called
# from the new instance of class Two()
模塊mod_two.py:
class Two:
def __init__(self):
# Call call_back_func() of module mod_one
我發現的唯一途徑是通過回調函數call_back_func()作爲第二類的參數,如下所示:
self.new_instance = Two(self.call_back_func)
但我想知道是否有更好的方法來做到這一點。
這是一個非常有效的方法,因爲它不會引入循環依賴。 – 2011-12-21 18:29:15
我認爲將'self.call_back_func'傳遞給構造函數是一個很好的方法。 – NPE 2011-12-21 18:29:17