python - 将值传递给类

标签 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

是否有某种方法可以将变量operatorId传递给实例,以便我可以在类中的方法getId中使用?

谢谢!

最佳答案

您只需将其作为参数传递给__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,这并不完全正确,但由于您没有使用,所以我将忽略该问题。 :)

关于python - 将值传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25383901/

相关文章:

python - 使用 AF_UNIX 套接字的双向通信

javascript - 私有(private)方法使用或不使用函数的困惑

java - 当子对象状态影响父状态时处理它

python - 在 Pandas DataFrame 中除以两个数字时出现奇怪的错误

python - Pandas系列——记录数值变化

python - 嵌套类更清晰的继承?

javascript - 有没有办法用 JavaScript 在 HTML 中强制硬编码样式?

design-patterns - 如何设计带有非面向对象部分的 UML 类图?

java - 如何在处理中将矩形平移到先前的鼠标坐标

php - 在 oop 中设置全局变量的最佳方法?