<p>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 concept here is composition. However, composition doesn't necessarily mean nesting, right?</p>

<p>I have code that looks something like this:</p>

<pre><code>class DownloadThread:
    def foo(self):
        pass

class DownloadManager():
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadThread())
</code></pre>

<p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p>

<pre><code>class DownloadManager():
    class DownloadThread:
        def foo(self):
            pass
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadManager.DownloadThread())
</code></pre>

[{'answer_id': 78858, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 8, 'selected': True, 'text': '<p>You might want to do this when the "inner" class is a one-off, which will never be used outside the <em>definition</em> of the outer class. For example to use a metaclass, it\'s sometimes handy to do</p>\n\n<pre><code>class Foo(object):\n    class __metaclass__(type):\n        .... \n</code></pre>\n\n<p>instead of defining a metaclass separately, if you\'re only using it once.</p>\n\n<p>The only other time I\'ve used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together:</p>\n\n<pre><code>class Group(object):\n    class cls1(object):\n       ...\n\n    class cls2(object):\n       ...\n</code></pre>\n\n<p>Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.</p>\n'}, {'answer_id': 78868, 'author': 'André Chalella', 'author_id': 4850, 'author_profile': 'https://Stackoverflow.com/users/4850', 'pm_score': 5, 'selected': False, 'text': "<p>I don't know Python, but your question seems very general. Ignore me if it's specific to Python.</p>\n\n<p>Class nesting is all about scope. If you think that one class will only make sense in the context of another one, then the former is probably a good candidate to become a nested class.</p>\n\n<p>It is a common pattern make helper classes as private, nested classes.</p>\n"}, {'answer_id': 78968, 'author': 'tim.tadh', 'author_id': 14107, 'author_profile': 'https://Stackoverflow.com/users/14107', 'pm_score': 3, 'selected': False, 'text': "<p>You could be using a class as class generator. Like (in some off the cuff code :)</p>\n\n<pre><code>class gen(object):\n    class base_1(object): pass\n    ...\n    class base_n(object): pass\n\n    def __init__(self, ...):\n        ...\n    def mk_cls(self, ..., type):\n        '''makes a class based on the type passed in, the current state of\n           the class, and the other inputs to the method'''\n</code></pre>\n\n<p>I feel like when you need this functionality it will be very clear to you. If you don't need to be doing something similar than it probably isn't a good use case.</p>\n"}, {'answer_id': 79094, 'author': 'Jerub', 'author_id': 14648, 'author_profile': 'https://Stackoverflow.com/users/14648', 'pm_score': 3, 'selected': False, 'text': "<p>There is really no benefit to doing this, except if you are dealing with metaclasses.</p>\n\n<p>the class: suite really isn't what you think it is. It is a weird scope, and it does strange things. It really doesn't even make a class! It is just a way of collecting some variables - the name of the class, the bases, a little dictionary of attributes, and a metaclass.</p>\n\n<p>The name, the dictionary and the bases are all passed to the function that is the metaclass, and then it is assigned to the variable 'name' in the scope where the class: suite was.</p>\n\n<p>What you can gain by messing with metaclasses, and indeed by nesting classes within your stock standard classes, is harder to read code, harder to understand code, and odd errors that are terribly difficult to understand without being intimately familiar with why the 'class' scope is entirely different to any other python scope.</p>\n"}, {'answer_id': 49812827, 'author': 'Thomas', 'author_id': 4540266, 'author_profile': 'https://Stackoverflow.com/users/4540266', 'pm_score': 4, 'selected': False, 'text': '<p>There is another usage for nested class, when one wants to construct inherited classes whose enhanced functionalities are encapsulated in a specific nested class.</p>\n\n<p>See this example:</p>\n\n<pre><code>class foo:\n\n  class bar:\n    ...  # functionalities of a specific sub-feature of foo\n\n  def __init__(self):\n    self.a = self.bar()\n    ...\n\n  ...  # other features of foo\n\n\nclass foo2(foo):\n\n  class bar(foo.bar):\n    ... # enhanced functionalities for this specific feature\n\n  def __init__(self):\n    foo.__init__(self)\n</code></pre>\n\n<p>Note that in the constructor of <code>foo</code>, the line <code>self.a = self.bar()</code> will construct a <code>foo.bar</code> when the object being constructed is actually a <code>foo</code> object, and a <code>foo2.bar</code> object when the object being constructed is actually a <code>foo2</code> object. </p>\n\n<p>If the class <code>bar</code> was defined outside of class <code>foo</code> instead, as well as its inherited version (which would be called <code>bar2</code> for example), then defining the new class <code>foo2</code> would be much more painful, because the constuctor of <code>foo2</code> would need to have its first line replaced by <code>self.a = bar2()</code>, which implies re-writing the whole constructor. </p>\n'}, {'answer_id': 66900415, 'author': 'Leon Chang', 'author_id': 9749972, 'author_profile': 'https://Stackoverflow.com/users/9749972', 'pm_score': 0, 'selected': False, 'text': "<p>Either way, defined inside or outside of a class, would work. Here is an employee pay schedule program where the helper class EmpInit is embedded inside the class Employee:</p>\n<pre><code>class   Employee:\n\n    def level(self, j):\n        return j * 5E3\n\n    def __init__(self, name, deg, yrs):\n        self.name = name\n        self.deg = deg\n        self.yrs = yrs\n        self.empInit = Employee.EmpInit(self.deg, self.level)\n        self.base = Employee.EmpInit(self.deg, self.level).pay\n\n    def pay(self):\n        if self.deg in self.base:\n            return self.base[self.deg]() + self.level(self.yrs)\n        print(f&quot;Degree {self.deg} is not in the database {self.base.keys()}&quot;)\n        return 0\n\n    class   EmpInit:\n\n        def __init__(self, deg, level):\n            self.level = level\n            self.j = deg\n            self.pay = {1: self.t1, 2: self.t2, 3: self.t3}\n\n        def t1(self):   return self.level(1*self.j)\n        def t2(self):   return self.level(2*self.j)\n        def t3(self):   return self.level(3*self.j)\n\nif  __name__ == '__main__':\n    for loop in range(10):\n        lst = [item for item in input(f&quot;Enter name, degree and years : &quot;).split(' ')]\n        e1 = Employee(lst[0], int(lst[1]), int(lst[2]))\n        print(f'Employee {e1.name} with degree {e1.deg} and years {e1.yrs} is making {e1.pay()} dollars')\n        print(&quot;EmpInit deg {0}\\nlevel {1}\\npay[deg]: {2}&quot;.format(e1.empInit.j, e1.empInit.level, e1.base[e1.empInit.j]))\n</code></pre>\n<p>To define it outside, just un-indent EmpInit and change Employee.EmpInit() to simply EmpInit() as a regular &quot;has-a&quot; composition. However, since Employee is the controller of EmpInit and users don't instantiate or interface with it directly, it makes sense to define it inside as it is not a standalone class. Also note that the instance method level() is designed to be called in both classes here. Hence it can also be conveniently defined as a static method in Employee so that we don't need to pass it into EmpInit, instead just invoke it with Employee.level().</p>\n"}, {'answer_id': 68819173, 'author': 'kharandziuk', 'author_id': 1907902, 'author_profile': 'https://Stackoverflow.com/users/1907902', 'pm_score': 1, 'selected': False, 'text': '<p>A good use case for this feature is Error/Exception handling, e.g.:</p>\n<pre><code>class DownloadManager(object):\n    class DowndloadException(Exception):\n        pass\n\n    def download(self):\n        ...\n</code></pre>\n<p>Now the one who is reading the code knows all the possible exceptions related to this class.</p>\n'}]
['https://Stackoverflow.com/questions/78799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10708/']