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

后端 未结 5 1873
栀梦
栀梦 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 11:18

    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

    class Foo(object):
        class __metaclass__(type):
            .... 
    

    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:

    class Group(object):
        class cls1(object):
           ...
    
        class cls2(object):
           ...
    

    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.

提交回复
热议问题