【问题标题】:Is there a simpler way to pass variables from the outer class to an inner class?有没有更简单的方法将变量从外部类传递到内部类?
【发布时间】:2021-10-20 12:21:24
【问题描述】:

如果我有下面的类,有没有办法将外部类__init__构造函数中定义的变量传递给内部类的内部类构造函数?

class Outer:

     def __init__(self, df):
        self.df = df

     class Inner:
          ## Looking to pass the df into this class

我偶然发现了this 解决方案,但我想知道是否有更简单的解决方案?

我也遇到了this 解决方案,但是有了这个,我必须在调用内部类时插入 df。有没有办法避免这种情况,如果它在外部类中初始化,我可以在调用内部类时自动检索它,还是这是不可避免的?

【问题讨论】:

  • 你为什么要这样做?你是如何设计你的程序的?
  • “嵌套类”之间没有内在联系。您也可以将它们写成不嵌套,并排,以获得相同的效果。所以不,没有固有的方法。
  • @BeChillerToo 尝试制作一类自定义股票指标,然后作为私有模块存储在 github 上,然后导入 python。我想避免初始化__init__.py 文件中的所有其他类,而是调用一个外部类来访问其他类。有不少。
  • @deceze 好的,谢谢。

标签: python dataframe class


【解决方案1】:

在创建内部对象之前,您没有内部对象,此时您可以传递外部类的任何属性:

class Outer:
     def __init__(self, df):
        self.df = df
        self._inner = self.Inner(self.df)

     class Inner:
         def __init__(self, parent_df):
            self.parent_df = parent_df 

另见Is it good practice to nest classes?

【讨论】:

  • 好吧,很像我原帖中的第二个链接。估计到时候就无法避免了。谢谢!
【解决方案2】:
class Outer:

    def __init__(self, df):
        self.df = df

    class Inner(Outer):
        pass

Inner 现在将继承 Outer 的属性和方法

【讨论】:

  • 有了这个缩进你会得到NameError: name 'Outer' is not defined
  • @Matthias 谢谢,已修复
  • 感谢您的回复。正如我对@BeChillerToo 的评论所指出的那样,这就是我所避免的。但是,如果没有这样做的固有方法,我将不得不依赖它。谢谢!
  • @JackGoodall 在您的缩进编辑之后,这会带来一个错误'Outer' is not defined,正如@Matthias 在他的评论中所说的那样。它在被视为单独的类而不是嵌套类时起作用。不管怎样,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 2013-09-20
  • 2021-08-21
  • 1970-01-01
相关资源
最近更新 更多