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

后端 未结 5 1881
栀梦
栀梦 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:14

    There is really no benefit to doing this, except if you are dealing with metaclasses.

    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.

    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.

    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.

提交回复
热议问题