
示例代码:
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'总结
以上是内存溢出为你收集整理的python – 从该类内部的类调用实例变量全部内容,希望文章能够帮你解决python – 从该类内部的类调用实例变量所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)