I am trying to write a Python class capable of doing the following:
c = MyClass()
a = c.A("a name for A")
b = c.B("a name for B")
A and B can be any (well, they are defined in the database, but I do not want to explicitly define them in my code)
A hacky workaround for him would be to do the following:
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
This will work when the user calls something like:
a = c.A("nameA")
b = c.B("nameB")
However, it will fall in situations where function pointers are stored without calling:
aFunc = c.A
bFunc = c.B
aFunc("nameA")
bFunc("nameB")
Any suggestions for something I don't see here?
thank
Edit: I seem to have just figured this out, but Philip has a much more elegant solution ....
My solution was:
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
In the version I actually used (since I needed a more difficult task than one argument): (I don’t know if this can be done using the lambda function ...)
def __getattr__(self, attrName):
def find_entity_wrapper(*args, **kwargs):
return self.find_entity(attrName, *args, **kwargs)
return find_entity_wrapper