在Python的另一个类中定义一个类是否有好处

在Python的另一个类中定义一个类是否有好处

本文介绍了在Python的另一个类中定义一个类是否有好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里谈论的是嵌套类.本质上,我有两个正在建模的类.一个DownloadManager类和一个DownloadThread类.这里显而易见的OOP概念是组合.但是,组合不一定意味着嵌套,对吧?

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:

class DownloadThread:
    def foo(self):
        pass

class DownloadManager():
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadThread())

但是现在我想知道是否存在嵌套更好的情况.像这样:

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

class DownloadManager():
    class DownloadThread:
        def foo(self):
            pass
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadManager.DownloadThread())

推荐答案

当内部"类是一次性的,永远不会在定义之外使用时,您可能想执行此操作外层阶级.例如,使用元类有时会很方便

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):
       ...

然后从另一个模块中,您可以导入Group并将它们称为Group.cls1,Group.cls2等.但是,有人可能会争辩说,使用模块可以完成完全相同的工作(也许以一种不太混乱的方式).

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.

这篇关于在Python的另一个类中定义一个类是否有好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:33