3

I have a class that has a logger instance variable, and I am creating another class inside of that and I want to use the logger instance variable inside of that class, but not sure how to call it.

Example Code:

class A():
    def __init__(self):
        self.logger = Logger.get() #this works fine didn't include the Logger class

    def func(self):
        class B():
            def __init__(self):
                self.a = 'hello'
            def log(self):
            #How do I call A's logger to log B's self.a
            #I tried self.logger, but that looks inside of the B Class

2 Answers 2

7

As the Zen of Python states, "Flat is better than nested." You could un-nest B, and pass the logger as an argument to B.__init__. By doing so,

  • You make clear what variables B depends on.
  • B becomes easier to unit test
  • B may be reused in other situations.

class A():
    def __init__(self):
        self.logger = Logger.get() #this works fine didn't include the Logger class

    def log(self):
        b = B(self.logger)

class B():
    def __init__(self, logger):  # pass the logger when instantiating B
        self.a = 'hello'
Sign up to request clarification or add additional context in comments.

Comments

5

The name self isn't a language requirement, it's merely a convention. You can use a different variable name like a_self so the outer variable isn't masked.

class A():
    def __init__(self):
        self.logger = Logger.get() #this works fine didn't include the Logger class

    def func(a_self):
        class B():
            def __init__(self):
                self.a = 'hello'
            def log(self):
                a_self.logger.log('...')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.