[Tutor] metaclass question

Kent Johnson kent37 at tds.net
Tue Jan 23 02:14:48 CET 2007


Kim Branson wrote:
> 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.

Do you need to be passing in the unique method, or can you just make a 
base class with the common methods and subclasses that define their 
unique methods? For example,

class Base(object):
   def a(self):
     pass
   def b(self):
     pass
   def calculateResults(self):
     raise NotImplementedError

class A(Base):
   def calculateResults(self):
     return self.a() * self.b()

class B(Base):
   def calculateResults(self):
     return dict(a=self.a(), b=self.b())

Kent



More information about the Tutor mailing list