1
我發現創建在某些邏輯中包裝參數化對象屬性的「方法工廠函數」很有用。將類屬性作爲參數的方法工廠
例如:
"""Fishing for answers.
>>> one().number_fisher()
'one fish'
>>> one().colour_fisher()
'red fish'
>>> two().number_fisher()
'two fish'
>>> two().colour_fisher()
'blue fish'
"""
class one(object):
def number(self):
return 'one'
def colour(self):
return 'red'
def _make_fisher(sea):
def fisher(self):
return '{0} fish'.format(getattr(self, sea)())
return fisher
number_fisher = _make_fisher('number')
colour_fisher = _make_fisher('colour')
class two(one):
def number(self):
return 'two'
def colour(self):
return 'blue'
是有必要的屬性make_fisher
作爲一個字符串傳遞,還是有更好的方法來做到這一點?
如果我傳遞並使用實際屬性,則會破壞多態性,因爲two
的實例仍將對屬性對象使用相同的引用。
I.E.
diff --git a/fishery.py b/fishery.py
index 840e85d..b98cf72 100644
--- a/fishery.py
+++ b/fishery.py
@@ -4,10 +4,12 @@
'one fish'
>>> one().colour_fisher()
'red fish'
+
+This version does not implement polymorphism, and so this happens:
>>> two().number_fisher()
-'two fish'
+'one fish'
>>> two().colour_fisher()
-'blue fish'
+'red fish'
"""
@@ -18,10 +20,10 @@ class one(object):
return 'red'
def _make_fisher(sea):
def fisher(self):
- return '{0} fish'.format(getattr(self, sea)())
+ return '{0} fish'.format(sea(self))
return fisher
- number_fisher = _make_fisher('number')
- colour_fisher = _make_fisher('colour')
+ number_fisher = _make_fisher(number)
+ colour_fisher = _make_fisher(colour)
class two(one):
def number(self):
似乎有點弱,不得不使用字符串引用屬性,但我沒有看到另一種方式來做到這一點。在那兒?