向类传递值

2024-10-02 12:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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中使用它吗?你知道吗

谢谢!你知道吗


Tags: selfnonereturnifdefiniclassfile
1条回答
网友
1楼 · 发布于 2024-10-02 12:28:01

您只需要将它作为参数传递给__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,这并不是完全正确的,但是既然您没有,我将忽略这个问题。:)

相关问题 更多 >

    热门问题