我有一个具有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
正如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'