我想写出具有执行以下操作的能力的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