3

我有一门课,有时我想“重置”。与其手动清除类中的所有变量及其使用的所有模块,我认为通过调用自身的init来重构它可能是一个好主意。我担心的是我不太确定这是否是一个好的模式,或者 GC 是否正确清除了旧对象。

下面是一个例子:

from modules import SmallClass
from modules import AnotherClass

class BigClass(object):
    def __init__(self, server=None):
        """construct the big class"""
        self.server = server
        self.small_class = SmallClass(self.server)
        self.another_class = AnotherClass(small_class)

    def reset_class(self):
        """reset the big class"""
        self.__init__(self.server)

这会导致问题,还是有更好的方法来解决这个问题?

4

2 回答 2

5

我建议反过来做:

from modules import SmallClass
from modules import AnotherClass

class BigClass(object):
    def __init__(self, server=None):
        """construct the big class"""
        self.reset_class(server)

    def reset_class(self, server=None):
        """reset the big class"""
        self.server = server
        self.small_class = SmallClass(self.server)
        self.another_class = AnotherClass(small_class)

这种模式很常见,因为它允许__init__重置类,您也可以单独重置类。我还在其他面向对象的语言(例如 Java)中看到了这种模式。

于 2013-11-07T18:30:12.557 回答
2

__init__这样做很安全,除了自动调用之外没有什么神奇的。

但是,正常的做法是将通用代码重构到您的reset_class方法中(我称之为resetbtw,类已经在类名中)。然后只需reset__init__方法中调用。

于 2013-11-07T18:30:54.627 回答