2013-07-16 39 views
0

對於問題的笨拙標題很抱歉,但我想不出一種合適的方式來表達它。我正在Python 2.7中處理日曆類型的應用程序。我有一個類Day它的形式當我有多個項目時,如何間接引用一個類中定義的方法

def __init__(self, d): 
    # Date in datetime.date format 
    self.date = d 

    # Julian date 
    self.julian = date_utils.calendar_util.gregorian_to_jd(d.year, d.month, d.day) 

    # Sun and moon rise and set times 
    self.sun = RiseSet() 
    self.moon = RiseSet() 

... 

def SetSunRise(self, t): 
    assert type(t) is datetime.time 
    self.sun.rise = t 

def SetSunSet(self, t): 
    assert type(t) is datetime.time 
    self.sun.set = t 

其中RiseSet是一個簡單的類的構造函數:

def __init__(self, r=None, s=None): 
# rise (r) and set (s) times should normally be datetime.time types 
# but it is possible for there to 
# be no sun/moon rise/set on a particular day so None is also valid. 

    if r is not None: 
     assert type(r) is datetime.time 
    if s is not None: 
     assert type(s) is datetime.time 
    if r is not None and s is not None: 
     assert r < s 

    self.rise = r 
    self.set = s 

顯然有每天在特定的日曆Day對象。這些包含在名爲days的字典中(鍵入datetime.date)。現在我有四個列表,其中包含相關時期的日出/月份上升/設置時間:sunrisessunsetsmoonrises, moonsets並且想要設置的日出/月份上升/設置時間爲days

現在我可以只有四個獨立的循環遍歷四個列表中的每一個。但我真正想要做的實際上是使用類似指針的函數,所以我可以有這樣的事情:

for (func, obj) in zip([Day.SetSunRise, Day.SetSunSet, Day.SetMoonRise, Day.SetMoonSet], [sunrises, sunsets, moonrises, moonsets]) 

所以有效地我想要做的就是一個指向一個功能,但基於類定義不是該類的單個對象/實例。我敢肯定,一定有一些簡單,優雅的方式來做到這一點,但我目前難住。

有人嗎?

回答

1

你幾乎在那裏。你可以做到這一點,請參閱Day類中的未綁定方法,然後在實例中傳遞以調用該方法。

換句話說:Day.SetSunRise是未綁定方法的引用等着你用Day()實例調用它:

someday = Day() 
Day.SetSunRise(someday, some_sunrise_time) 

未綁定的方法,如功能,是對象,你可以將它們存儲在列表中,等:

for meth, timestamp in zip([Day.SetSunRise, Day.SetSunSet], [sunrise, sunset]): 
    meth(someday, timestamp) 

現在,所有你需要做的是循環在你的日落,日出你,等那些拉鍊向上(或以其他方式將它們組合)與它們匹配Day實例,併爲您調用該方法。

+0

非常感謝。非常簡單(當有人告訴你如何!) – TimGJ

相關問題