将值传递给类

时间:2014-08-19 12:50:27

标签: python oop

我在Python中有这个抽象类:

class TransactionIdsGenerator(object):

  def getId(self):
      raise NotImplementedError

这个实现的类:

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

在其他文件中,我有类的实例:

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

是否可以通过某种方式将varibale operatorId传递给实例,以便我可以在类中的 getId 方法中使用?

谢谢!

1 个答案:

答案 0 :(得分:2)

您只需将其作为参数传递给__init__。 (请注意,在您当前的代码中,您甚至不需要定义TransactionIdsGeneratorGeneric.__init__,因为它唯一要做的就是调用父__init__。)

class TransactionIdsGeneratorGeneric(TransactionIdsGenerator):

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

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

然后在实例化类时:

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

关键是,只要您确保传递正确的参数,子类__init__不需要与父级具有完全相同的签名。你打电话给父母。如果您正在使用super,这并不完全正确,但由于您不是,我将忽略该问题。 :)