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

2024-04-26 18:59:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类有一个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

Tags: the实例代码selflog示例getinit
2条回答

名称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('...')

正如Python的Zen所说,“Flat比nested好。”您可以取消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'

相关问题 更多 >