Technically, you don't need metaclasses probably: class A(object): def methA(self, abc): pass def methB(self, def, ghi): pass def defaultMethod(self): raise UnknownMethodError() def __init__(self, methodName): self._calc = getattr(self, "meth%s" % methodName, self.defaultMethod) def calcResult(self, *args, **kw): return self._calc(*args, **kw)
a=A("A") b=A("B") a.calcResult(123) b.calcResult(234, 345) a.calcResult(1,2) => TypeError b.calcResult(1) => TypeError metaclasses in Python are a way to get control of the class creation process. E.g. it's quite useful if you need to do some changes to some classes, no matter what. (E.g. I've implemented a class where methods can be synchronized (by using a lock) with a metaclass => the meta class makes sure that all methods get wrapped with a function that acquires and releases the needed locks.) Andreas * Kim Branson <[EMAIL PROTECTED]> [070122 23:51]: > Hi i'm interested in implementing a factoryclass in python > > What i'd like to do is have my factoryClass produce an instance of a > class with some methods defined in arguments to the factory class. > > The classes that are produced have many common methods, but a single > unique method. This method actually is a series of calls to a c++ api. > Depending on what we are doing with the produced class, i'd like the > unique method to call api function A, or api function B etc. > Alternatively the unique method might call A and the B and return a > dict of the results. > > I'm doing this because i'd like all my produced class instances to > simply have a calculateResults method which will then go and do the > right thing. I don't want to set some values in the init, like A== > True and have a if A: call methodA etc statement. > > I'm not sure if a factory class is the best way to solve this > problem, but i can see future cases where the unique function will > need to do many things with intermediate results before returning the > results dict. i think a factory class might be the best way of > ensuring an extensible design. > > So whats the best way to do this. I have found many references to > creating a class with __metaclass__ = SomeMetaClass, but i don't see > how one can pass arguments to the meta class. > > An alternative might be to have a class that operates on an existing > instance and adds the correct method, but this seems slightly clunky, > and is probably not the python way > > > Cheers > > Kim > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor