Is there a benefit to defining a class inside another class in Python?

后端 未结 5 1872
栀梦
栀梦 2020-12-04 10:46

What I\'m talking about here are nested classes. Essentially, I have two classes that I\'m modeling. A DownloadManager class and a DownloadThread class. The obvious OOP conc

5条回答
  •  -上瘾入骨i
    2020-12-04 11:19

    There is another usage for nested class, when one wants to construct inherited classes whose enhanced functionalities are encapsulated in a specific nested class.

    See this example:

    class foo:
    
      class bar:
        ...  # functionalities of a specific sub-feature of foo
    
      def __init__(self):
        self.a = self.bar()
        ...
    
      ...  # other features of foo
    
    
    class foo2(foo):
    
      class bar(foo.bar):
        ... # enhanced functionalities for this specific feature
    
      def __init__(self):
        foo.__init__(self)
    

    Note that in the constructor of foo, the line self.a = self.bar() will construct a foo.bar when the object being constructed is actually a foo object, and a foo2.bar object when the object being constructed is actually a foo2 object.

    If the class bar was defined outside of class foo instead, as well as its inherited version (which would be called bar2 for example), then defining the new class foo2 would be much more painful, because the constuctor of foo2 would need to have its first line replaced by self.a = bar2(), which implies re-writing the whole constructor.

提交回复
热议问题