我在这里讨论的是嵌套类。基本上,我有两个我正在建模的类。 DownloadManager类和DownloadThread类。这里明显的OOP概念是组合。但是,构图并不一定意味着嵌套,对吧?在Python的另一个类中定义一个类是否有好处?
我有一些代码看起来是这样的:
class DownloadThread:
def foo(self):
pass
class DownloadManager():
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadThread())
但现在我不知道是否有一个情况下筑巢会更好。例如:
class DownloadManager():
class DownloadThread:
def foo(self):
pass
def __init__(self):
dwld_threads = []
def create_new_thread():
dwld_threads.append(DownloadManager.DownloadThread())
我-would-认为,在第二种情况下,你会-definitely-使用一个模块或包,它被设计为命名空间得到更好的服务。 – 2008-09-17 03:51:33
这是一个梦幻般的答案。简单点,并提到使用模块的替代方法。 +1 – CornSmith 2013-05-08 16:19:44
为了记录,对于那些固执地拒绝或不能将他们的代码组织到分层包和适当模块中的人来说,使用类作为名称空间有时可能比不使用任何东西更好。 – 2014-04-07 19:05:57