jvrdom
jvrdom

Reputation: 368

Passing values to class

I have this abstract class in Python:

class TransactionIdsGenerator(object):

  def getId(self):
      raise NotImplementedError

And this class that implements:

class TransactionIdsGeneratorGeneric(TransactionIdsGenerator):

  INI_FILE = '/platpy/inifiles/postgres_config.ini'    
  __dbManager = None

  def __init__(self):
     TransactionIdsGenerator.__init__(self)

  def getId(self):
     _ret = None
     _oDbManager = self.__getDbManager()
     if _oDbManager.execQuery("select nextval('send_99_seq');"):
         _row = _oDbManager.fetchOne()
         if _row is not None:
             _ret = _row[0]
     return _ret

  def __getDbManager(self):
     if self.__dbManager is None:
        self.__dbManager = PostgresManager(iniFile=self.INI_FILE)

     return self.__dbManager

And in other file i have the instance of the class:

  def __getTransactionIdsGenerator(self, operatorId):
      _ret = TransactionIdsGeneratorGeneric()
      return _ret

Is some way to pass the varibale operatorId to the instance, so i can use in the method getId in the class?

Thanks!

Upvotes: 1

Views: 101

Answers (1)

chepner
chepner

Reputation: 532428

You just need to pass it as an argument to __init__. (Note that in your current code, you don't even need to define TransactionIdsGeneratorGeneric.__init__, since the only thing it does is call the parent's __init__.)

class TransactionIdsGeneratorGeneric(TransactionIdsGenerator):

    INI_FILE = '/platpy/inifiles/postgres_config.ini'    
    __dbManager = None

    def __init__(self, opid):
        TransactionIdsGenerator.__init__(self)
        self.opid = opid

Then when you instantiate the class:

def __getTransactionIdsGenerator(self, operatorId):
  _ret = TransactionIdsGeneratorGeneric(operatorId)
  return _ret

The key is that the child class's __init__ doesn't need to have the exact same signature as the parent's, as long as you make sure the correct arguments are passed to the parent when you call it. This isn't entirely true if you are making use of super, but since you aren't, I'll ignore that issue. :)

Upvotes: 2

Related Questions