在 Python 中的嵌套 classes 中使用 class 的变量

Using varibles of a class inside nested classes in Python

我想要这样的东西。我无法将父实例传递给 Child class

 class Outer:
    def __init__(self, logging):
        self.logging 
        self.logger = logging.getLogger('Parent')

    class Inner(SomeBaseClass):
        def __init__(self, *args):
            Outer.logger.info('initializing Child with %', ' '.join(args))

  logging.config.fileConfig('logging.conf')
  outerObject = Outer(logging)
  .
  .

  .
  # both inner1 and inner2 use same logger object
  # intent: no need to pass the logger
  inner1 = outerObject.Inner('xyzz')
  inner2 = outerObject.Inner('abc')

如何实现?或任何更好的方法来做同样的事情?

getLogger 旨在让您始终可以通过将正确的名称作为参数传递来检索所需的 Logger 实例。您也不需要将 logging 模块的引用传递给 Outer.__init__

class Outer:
    def __init__(self):
        self.logger = logging.getLogger('Parent')

    class Inner(SomeBaseClass):
        def __init__(self, *args):
            logger = logging.getLogger('Parent')
            logger.info('initializing Child with %', ' '.join(args))

请注意,对于 Outer 的任何特定实例,Outer.logger 将不同于 self.logger

class Inner(SomeBaseClass):
    def __init__(self, logger, *args):
        self.logger = logger
        self.logger.info('initializing Child with %', ' '.join(args))

class Outer(object):
    def __init__(self, logging, logger_name='Parent'):
        self.logging = logging
        self.logger = self.logging.getLogger(logger_name)

    def get_inner(self, *args):
        return Inner(self.logger, *args)

logging.config.fileConfig('logging.conf')
outerObject = Outer(logging)

inner1 = outerObject.get_inner('xyzz')
inner2 = outerObject.get_inner('abc')

好看吗?