我想弄清楚最傳統的Pythonic方法來進行有限的回調,以便與複雜對象的方法進行交互。我有一個通過通信渠道接收數據的程序,該數據分爲幾個不同的類別。我需要去耦哪個類別的數據是在確定,從數據的進一步處理:相當於Java內部類的代理的Python
class Categorizer(object):
'''Determines which category data is in.
There may be multiple variants of this class'''
def handleData(self, data, callback):
if self.somethingReallySpecial(data):
callback.onSomethingReallySpecial(data)
elif self.somethingSpecial(data):
callback.onSomethingSpecial(data)
else:
callback.onSomethingMundane(data)
# ... other methods ...
class IAmAReallyComplicatedBeast(object):
def __init__(self, categorizer, other_stuff):
self.categorizer = categorizer
# ...
# ... lots of other methods ...
def something(self, other_stuff):
data = self.obtain_data()
# this is probably wrong, but here's what I want to do:
beast = self
class Dispatcher(object):
def onSomethingMundane(data):
beast.doFoo(data)
def onSomethingSpecial(data):
beast.doBar(data)
def onSomethingReallySpecial(data):
beast.doBaz(data)
self.categorizer.handleData(data, Dispatcher())
def doFoo(self, data):
# for mundane data
def doBar(self, data):
# for special data
def doBaz(self, data):
# for really special data
在Java中我會用一個內部類(喜歡這裏的調度程序)...有一個Python化處理這個方法?
我不想直接把onSomethingXXX
方法對我IAmAReallyComplicatedBeast
類,有兩個原因:
- 這意味着我不得不爲是
- 我不使用這些名稱不希望
Categorizer
類可以任意訪問IAmAReallyComplicatedBeast
對象。也許這來自通常的Java偏執狂思維,但它對我來說似乎是一個很好的設計。
我會用'dispatch dict'。在Python中,字典可以保存函數。 – ch3ka 2014-10-28 16:39:09
我認爲內心階層總是正是你想要的,也許是最好的方式來做到這一點。這些大腿永遠不可能是pythonich,因爲python不是爲了做這種保護而設計的。 – 2014-10-28 17:51:01