从该类内部的类调用实例变量

Gre*_*own 3 python class

我有一个具有logger实例变量的类,我在其中创建了另一个类,我想在该类中使用logger实例变量,但不知道如何调用它.

示例代码:

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
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 7

正如Python的Zen所说,"Flat比嵌套更好".您可以取消嵌套B,并将记录器作为参数传递给B.__init__.通过这样做,

  • 您明确了变量所B依赖的内容.
  • B 变得更容易进行单元测试
  • B 可以在其他情况下重复使用.

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'
Run Code Online (Sandbox Code Playgroud)


Joh*_*ica 5

这个名称self不是语言要求,它只是一个惯例.您可以使用不同的变量名称,a_self因此外部变量不会被屏蔽.

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('...')
Run Code Online (Sandbox Code Playgroud)