我想寫出具有執行以下操作的能力的Python類:的Python:允許方法沒有特別的限制被稱爲ALA __getattr__
c = MyClass()
a = c.A("a name for A") # Calls internally c.create("A", "a name for A")
b = c.B("a name for B") # Calls internally c.create("B", "a name for B")
A和B可以是任何東西(當然,他們「再在數據庫中定義的,但我不希望在我的代碼明確定義它們)
它哈克解決方法是做到以下幾點:
class MyClass():
def __init__(self):
self.createItem = ""
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def create_wrapper(self, name):
self.create(self.createItem, name)
def __getattr__(self, attrName):
self.createItem = attrName
return self.create_wrapper
這將工作當U SER要求是這樣的:
a = c.A("nameA")
b = c.B("nameB")
然而,它會翻倒在情況下的函數指針存儲,而不叫:
aFunc = c.A
bFunc = c.B
aFunc("nameA") # Is actually calling c.create("B", "nameA"),
# as c.B was the last __getattr__() call
bFunc("nameB")
的任何東西,我在這裏失蹤有什麼建議?
感謝
編輯:我似乎已經只是想出這一個,但菲利普有一個更優雅的解決方案....
我的解決辦法是:
class MyClassCreator():
def __init__(self, origClass, itemType):
self.origClass = origClass
self.itemType = itemType
def create_wrapper(self, name):
return self.origClass.create(self.itemType, name)
class MyClass():
def __init__(self):
self.createItem = ""
def create(self, itemType, itemName):
print "Creating item %s with name %s" % (itemType, itemName)
def __getattr__(self, attrName):
return MyClassCreator(self, attrName).create_wrapper
版本我實際上最終使用(因爲我需要比單個參數更復雜)是:(我不知道這是否可以使用lambda函數來完成......)
def __getattr__(self, attrName):
def find_entity_wrapper(*args, **kwargs):
return self.find_entity(attrName, *args, **kwargs)
return find_entity_wrapper
你想實現一個'Mock'庫? – 2010-08-08 16:00:11