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

时间:2013-07-22 20:43:11

标签: 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

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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('...')