Skip to content
Advertisement

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

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?

I have code that looks something like this:

JavaScript

But now I’m wondering if there’s a situation where nesting would be better. Something like:

JavaScript

Advertisement

Answer

You might want to do this when the “inner” class is a one-off, which will never be used outside the definition of the outer class. For example to use a metaclass, it’s sometimes handy to do

JavaScript

instead of defining a metaclass separately, if you’re only using it once.

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement