问题描述
我在这里谈论的是嵌套类.本质上,我有两个正在建模的类.一个 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 中的另一个类中定义一个类是否有好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!