在Python中使用嵌套类中的类的varibles

时间:2015-05-12 15:17:11

标签: python class logging nested

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

 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')

如何实现这个?还是有更好的方法来做同样的事情?

2 个答案:

答案 0 :(得分:2)

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')

看起来不错?

答案 1 :(得分:0)

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.loggerself.logger的任何特定实例都不同于Outer