0

I want something like this. I cannot pass pass the parent instance to 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')

how to implement this? or any better method to do the same?

vanangamudi
  • 673
  • 1
  • 8
  • 21

2 Answers2

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

Looking good?

pavel_form
  • 1,760
  • 13
  • 14
0

getLogger is designed so that you can always retrieve the desired Logger instance by passing the right name as an argument. You don't need to pass a reference to the logging module to Outer.__init__, either.

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

Note that Outer.logger would be different than self.logger for any particular instance of Outer anyway.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • It is not just the logging module. I need to access some other instance variables of Outer class inside Inner Class. That is why I create a _parentObject_ and then use that object to create Inner class objects – vanangamudi May 12 '15 at 15:54
  • @vanangamudi read this http://stackoverflow.com/questions/2024566/access-outer-class-from-inner-class-in-python (inner classes in Python aren't like Java's) – sirfz May 12 '15 at 16:00