加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:22:51 所属栏目:Python 来源:网络整理
导读:我有一个具有logger实例变量的类,我正在创建另一个类,我想在该类中使用logger实例变量,但不知道如何调用它. 示例代码: class A(): def __init__(self): self.logger = Logger.get() #this works fine didn't include the Logger class def func(self): clas
我有一个具有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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读